Scanner wont work [duplicate] - java

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I have problem with Scanner
When I run the program it skips this one after
System.out.println("name");
n1=s.nextLine();
This is the program "CEmploye " is a class
package Ex5_2;
import java.util.*;
public class XXXX {
public static void main(String[] args) {
int input;
int c1 ;
String n1;
Date d1 = null;
float p1;
float [] t = new float[3];
System.out.println("give nb of emp");
Scanner s = new Scanner(System.in);
input=s.nextInt();
Vector v = new Vector(input);
for(int i=0 ;i <input;i++)
{
System.out.println("cin");
c1=s.nextInt();
System.out.println("name");
n1=s.nextLine();
System.out.println("price");
p1=s.nextFloat();
for(int k=0 ; k<3;k++)
{
System.out.println("nb of hour");
CEmploye.tab[k]=s.nextFloat();
}
CEmploye emp = new CEmploye(c1,n1,d1,p1);
emp.CalculSalaire();
System.out.println(emp.salaire);
}
}
}
Can anyone give me solution ?

System.in's buffer isn't flushed until it gets a newline. So you can't use nextInt() or nextFloat() because they block until a newline.
You'll need to read everything on a line by itself then parse it (with some validation as needed):
cl = Integer.parseInt(s.nextLine());
and
pl = Float.parseFloat(s.nextLine());
and
CEmploye.tab[k]=Float.parseFloat(s.nextLine());

You can't use n1=s.nextLine(); with n1=s.nextInt(). Use n1=s.next();

nextInt() only reads the next integer available and leaves a newline character in the inputstream.
Your s.nextLine() then gets consumed thus not prompting for additional inputs.
Simply add another nextLine() to read more lines

c1=s.nextInt();
This just reads the integer value not the end of line. So when you do
n1=s.nextLine();
it just reads the end of line that you provided by pressing the enter while providing the integer input for the previous variable (c1) and thus seems like it skipped the input. (If you put an integer and some string in the same line when taking c1 input, you will get values for c1 and n1 both. You can check the same)
In order to fix it, either put nextLine() input after each nextInt(). Hope it helps.

Related

Extracting data from scanner string passed into method

I am required to pass a scanner as a parameter to a method and have the method print things based on what was passed with the scanner.
So, if the scanner passed contains "6 fox 3 bees 2 25 8 ducks"
The method would print out
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks
I have no problem writing the method. I'm just confused as to how I would use a scanner to do that.
Well, a Scanner is used for reading stuff in from either a file or standard input (System.in). Passing it around wouldn't do you a whole lot of good unless you want to encapsulate functionality and responsibilities.
If we think about this from a problem-solving stance, what are we really trying to get?
We have a string that contains first a number and a string, and the second string could contain numerals.
All of these symbols are separated by space.
Everything is contained on one line; we don't have to worry about moving to the next line.
It's entirely up to you how you want to approach this, but a couple of suggestions are as follows:
Since you know the precise order of tokens, you can make multiple calls to Scanner.next() and Scanner.nextInt().
while(scanner.hasNext()) {
System.out.println(readFromScanner(scanner));
}
scanner.close(); // DO NOT DO THIS if you are using System.in!
public static String readFromScanner(Scanner scanner) {
StringBuilder result = new StringBuilder();
int times = scanner.nextInt();
String phrase = scanner.next();
for(int i = 0; i < times; i++) {
result.append(phrase);
}
return result.toString();
}
You could also read the entire line in at once using nextLine(), and parse it using String.split(), which gives you numerals at every even index (0, 2, 4, etc), and strings at every odd index (1, 3, 5, etc).
You can read from the Scanner using methods like next() and nextInt(). You can read the full Scanner javadoc here.
Try this. There are two ways of reading input.
1) InputStreamReader wrapped in a BufferedReader
2) Scanner classes in JDK1.5
Refer to this article. This will solve your problem.
http://www.mkyong.com/java/how-to-read-input-from-console-java/
You can pass a Parameter by :
Input Accept here
System.out.println("Input here: " );
String input = scan.next();
// This how you gonna pass the parameter
inputedByScanner(input);
Your Method Accept it and print the inputed value.
public void print inputedByScanner(String input){
System.out.println(input);
}
public class Homework {
public static void main(String[] args) {
System.out.println("Enter something:");
doStupidHomework(new Scanner(System.in));
}
private static void doStupidHomework(Scanner scanner) {
int i = 0, x = 0;
for (String next = scanner.next(); next != null; next = scanner.next(), i++) {
if (i % 2 == 0) {
x = Integer.parseInt(next);
continue;
}
for (int j = 0; j < x; j++) {
System.out.print(next);
}
System.out.println();
}
}
}
Output:
Enter something:
6 fox 3 bees 2 25 8 ducks
foxfoxfoxfoxfoxfox
beesbeesbees
2525
ducksducksducksducksducksducksducksducks

Java Using Scanner Multiple Times [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 26 days ago.
I am having this problem a lot. When I use a Scanner a lot of times, it doesn't get input from user.
Scanner scan = new Scanner(System.in);
System.out.println("1---");
int try1 = scan.nextInt();
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
String try3 = scan.nextLine();
System.out.println("4---");
String try4 = scan.nextLine();
When I run this code, result it :
1---
12
2---
321
3---
4---
aa
As you can see, it skipped at 3rd input. Why this is happening? I solve this problem by using new Scanners, sometimes I have 5-6 different Scanners and it looks so complicated.
Another problem is : there is an error "Resource leak: scan is never closed". I am really confused.
The problem is that by using scanner.nextInt() you only read an integer value, but not the whole line and you don't consume the newline character (\n) that is appended to the line when you press Enter.
Then, when you process reading with scanner.nextLine() you consume the newline character (\n) and from the previous row and don't read the line you want to read. In order to force it to read it, you have to add an additional input.nextLine() statement.
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
scan.nextLine(); //<-- fake statement, to move the cursor on the next line
String try3 = scan.nextLine();
Not related to the question, you have to close the Scanner, after finishing work, otherwise the compiler complains with a warning:
scan.close();
Use next API rather than nextLine as when you do nextInt you press enter and it generates number + \n and nextInt is only going to take an integer and won't take \n which in turn gets passed to next input i.e. try3 which is why it gets skipped.
Scanner scan = new Scanner(System.in);
System.out.println("1---");
int try1 = scan.nextInt();
System.out.println("2---");
int try2 = scan.nextInt();
System.out.println("3---");
String try3 = scan.next();
System.out.println("4---");
String try4 = scan.next();
Well, for the first question use
scan.next()
insted of using
scan.nextLine();
For the second question I'd recommend using try, assuming you need to close your scan as your compiler is warning: "Resource leak: scan is never closed"
Scanner scanner= null;
try {
scanner= new Scanner(System.in);
}
finally {
if(scanner!=null)
scanner.close();
}

Scanner and for loop [duplicate]

This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 8 years ago.
I'm working on a piece of code and I'm trying to initialize a vector. However, the code somehow skipped through the first one and initialized a blank to my vector. Anyone knows why? Here's a snippet of my code:
public class Test{
private Vector<String> vecStr;
public void run(){
vecStr = new Vector<String>();
System.out.println("How many strings do you want for your string vector?");
int numStr = keyboard.nextInt();
System.out.println("Enter your string values.");
for (int i=0;i<numStr;i++){
System.out.println(i + "Input");
vecStr.add(keyboard.nextLine());}
}
}
}
Let's say I input 4, somehow, the code gives me:
0
1
input:
2
input:
3
input:
It skipped the 0 one. Can someone please tell me why that happened? And if I were to display the Vector, it would give me : [ , blah, blah, blah]. How come there is a blank at the first element?
Scanner doesn't work on a line basis, but token basis. So, after your first nextInt() (for numStr) the scanner's cursor stays at the end of the input line (not start of next line). Therefore, first nextLine() execution right after that results in empty string. Subsequent calls to nextLine() then works correctly.
You can use input stream readers:
Vector<String> vecStr = new Vector<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("How many strings do you want for your string vector?");
int numStr = Integer.parseInt(reader.readLine());
System.out.println("Enter your string values:");
for (int i=0;i<numStr;i++){
System.out.println(i + " Input: ");
vecStr.add(reader.readLine());
}
System.out.println("vector contains:");
System.out.println(vecStr);

the next() method in the Scanner doen't wait for input

i wrote this line (String str = sc.next();) like 10 times in my code, and all of them work ok except for one that doesn't wait for my input and immediately throws an exception "java.util.NoSuchElementException" !
does any one have an idea why that could happen ??
private static Matrix GetRationalMatrix(int[] size) throws Exception {
Scanner sc = new Scanner(System.in);
MathVector[] matrix = new MathVector[size[0]];
for(int i = 0 ; i < size[0] ; i++) {
MathVector vector = null;
String str = sc.nextLine();
str = str.replaceAll("[ \t]+", " ");
String[] splitStr = str.split(" ");
Scalar[] scalarVector = new Scalar[size[1]];
for(int j = 0 ; j < splitStr.length ; j++) {
String[] tmp = splitStr[j].split("/");
try {
scalarVector[j] = new Rational(Integer.parseInt(tmp[0]), Integer.parseInt(tmp[1]));
}
catch(Exception e){
sc.close();
throw new Exception("Please enter values properly: a/b were a,b are integers!");
}
}
vector = new MathVector(size[1], scalarVector);
matrix[i] = new MathVector(vector);
}
Matrix ans = new Matrix(size[0], matrix);
sc.close();
return ans;
}
in size[0] the number of rows and in size[1] number of columns , both will be positive integers
nextLine() instead of next();
Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.
If you previously used
Scanner sc = new Scanner(System.in);
inside a try-with-resources or closed the Scanner yourself, that would have closed the underlying System.in stream. In that case, trying to read from it again through a Scanner would cause a NoSuchElementException.
Don't close System.in and try to re-use the same Scanner object.
java.util.NoSuchElementException is a RuntimeException which can be thrown by different classes in Java like Iterator, Enumerator, Scanner or StringTokenizer. All of those classes has method to fetch next element or next tokens if underlying data-structure doesn't have any element Java throws "java.util.NoSuchElementException".
u can use a string tokenizer in our code..
StringTokenizer st=new StringTokenizer(sc);
u can use hasMoretokens() method....so that it returns true as long as the input u provided have more tokens..... incase u want to get next token u can nextToken() method...
The javadoc for hasNext() specifies:
Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.
The javadoc for next() specifies:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
That does not mean next() will always block, but it might block, say if it's waiting for the end of the token, since it promises to return the next complete token from the input. Checking whether the input contains another token is an entirely different operation, performed by hasNext(), which will block because it will wait for input (until EOF is found).
So I think you're getting NoSuchElementException because you are using next() improperly.

list.add(String) in LinkedList doesnt work properly for me

I want write program with this functionality:
User will input how many things he have. He will input these things and things will be added to the list.
I made this code :
public class lists {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
LinkedList<String> list= new LinkedList<String>();
System.out.println("How many things you have?");
int size=input.nextInt();
LinkedList<String> list= new LinkedList<String>();
System.out.println("Enter those things");
for(int c=1;c<=size;c++) list.add(input.nextLine().toString());
System.out.printf("%s",list);
}
}
For example Output for number 5 looks like this:
[, 1st Inputed, 2nd Inputed,3rd Inputed, 4nd inputed]
I want to know why the first String in the list is empty and it lets me input less things that I want. Thank you for your help.
Your code should be like this:
public class lists {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("How many things you have?");
int size=input.nextInt();
LinkedList<String> list= new LinkedList<String>();
System.out.println("Enter those things");
for(int c=0 ;c < size; c++)
{
String s = input.next();//use next() instead of nextLine()
list.add(s);
}
System.out.printf("%s",list);
}
}
Scanner.nextLine() as described in official document is:
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
After nextInt() is called it isn't properly terminating the allocated line of memory. So when nextLine() is called first time it is actually terminating the previous line that actually had value in it -- entered via nextInt() rather than taking in a new String value.That's why the String at index 0 of list is blank. So , in order to carry on reading the entered value rather than the previous blank line (because of non-termination of value returned by nextInt()) you can use Scanner.next() which according to official document states that:
Finds and returns the next complete token from this scanner.
The issue is that input.nextInt() does not consume the trailing newline, so the first input.nextLine() returns an empty string.
There are several ways to work around this. I'll leave it as an exercise to figure out how best to do it.

Categories