Java : Scanner odd behaviour [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 7 years ago.
I tried to get inputs via scanner and in the past, I use enter to get to the next set of inputs.
For ex.
Input 1 <enter>
Input 2 <enter>
However this time, it only accepts in the same line , taking spaces as delimiter.
Scanner in = new Scanner(System.in);
int a,b,n,t;
String input_line;
String inputs[]= new String[3];
t = in.nextInt();
in.reset(); //Tried resetting Scanner to see if this works
input_line = in.nextLine();
inputs = input_line.split(" ");
for(String s:inputs)
System.out.println(s);
For instance, I expect to take the variable t in first line and then move on to the second line for input_line scanning. But if I hit enter after entering t, the program ends.
What am I missing here?
(Merging with another question was suggested but , let me explain, the Scanner does not skip any inputs).

Without any testing I would think you would need something like this
Scanner in = new Scanner(System.in);
int a,b,n,t;
String input_line;
String[] input_numbers = new String[3];
t = in.nextInt();
in.nextLine();
input_line = in.nextLine();
while(!input_line.equals("")){
input_numbers = input_line.split(" ");
// do what you want with numbers here for instance parse to make each string variable into int or create new scanner to do so
input_line = in.nextLine();
}
}

Related

How to keep asking for user input until the input is empty? [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I want to make a while loop so that whenever a user inputs a blank input, it will re-ask the question until it is not empty. So far, I have this:
Scanner scn = new Scanner(System.in);
while (//user input is not blank) {
System.out.print("Enter id: ");
int id = scn.nextInt();
System.out.print("Enter name: ");
String last_name = scn.next();
System.out.print("Enter phone: ");
String first_name = scn.next();
scn.close();
break;
}
i'm pretty sure i'm over thinking this but i'm not sure of the syntax or the functions.
You should expect user to type say Quit/quit to quit rather than empty string.
You should close scanner out of loop without break.
You should use do...while loop instead if while loop. Something like:
do {
...
exit = scn.next();
} while (!exit.equalsIgnoreCase("quit"));
scn.close();

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);

Java Scanner doesn't wait for user input [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I am using Java's Scanner to read user input. If I use nextLine only once, it works OK. With two nextLine first one doesnt wait for user to enter the string(second does).
Output:
X: Y: (wait for input)
My code
System.out.print("X: ");
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();
Any ideas why could this happen? Thanks
It's possible that you are calling a method like nextInt() before. Thus a program like this:
Scanner scanner = new Scanner(System.in);
int pos = scanner.nextInt();
System.out.print("X: ");
String x = scanner.nextLine();
System.out.print("Y: ");
String y = scanner.nextLine();
demonstatres the behavior you're seeing.
The problem is that nextInt() does not consume the '\n', so the next call to nextLine() consumes it and then it's waiting to read the input for y.
You need to consume the '\n' before calling nextLine().
System.out.print("X: ");
scanner.nextLine(); //throw away the \n not consumed by nextInt()
x = scanner.nextLine();
System.out.print("Y: ");
y = scanner.nextLine();
(actually a better way would be to call directly nextLine() after nextInt()).

Java Scanner class reading strings [duplicate]

This question already has answers here:
Java Scanner class reading strings
(5 answers)
Closed 8 years ago.
I got the following code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.next();
}
System.out.println(names[0]);
When I run this code, the scanner will only pick up the first name and not the last name. And it will sometimes skip a line when trying to enter a name, it will show up as if I had left the name blank and skip to the next name. I don't know what's causing this.
I hope someone can help me!
EDIT: I have tried in.nextLine(); it fixes the complete names but it still keeps a line, here is an example of the output:
How many names are you going to save: 3
Type a name: Type a name: John Doe
Type a name: John Lennon
Instead of:
in.next();
Use:
in.nextLine();
nextLine() reads the characters until it finds a new line character '\n'
After your initial nextInt(), there's still an empty newline in your input. So just add a nextLine() after your nextInt(), and then go into your loop:
...
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine(); // gets rid of the newline after number-of-names
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
...
Scanner.next stops reading when it encounters a delimiter, which is a whitespace. Use the nextLine method instead.
Try using:
System.out.println()
Instead of:
System.out.print()

Categories