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

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()).

Related

Why there is no scanner.nextline() method between two nextInt() methods [duplicate]

This question already has answers here:
Why multiple nextInt() works?
(2 answers)
Closed 2 months ago.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number");
int FirstNumber = scanner.nextInt();
System.out.println("Entered First Number is" + FirstNumber);
System.out.println("Enter Second Number");
int SecondNumber = scanner.nextInt();
System.out.println("Entered Second Number is" + SecondNumber);
There is no error in the mentioned code everything is perfect but I have a doubt about why we didn't write a scanner.next line() method to handle enter key being pressed after the first number is entered on the console.
nextInt reads the next token in the scanner.
According to the documentation
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
And further down
The default whitespace delimiter used by a scanner is as recognized by Character.isWhitespace().
The documentation for Character.isWhitespace() says that it returns true if the given codepoint
[...]
[...] is '\n', U+000A LINE FEED.
[...]
Which means that \n is a separator, thus it's not part of any token, so you don't need to skip it with a dummy call to nextLine()
Scanner.nextInt() does not read new lines, it only progresses in the current line. See: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()

scanner doesn't wait for input when i used nextLine after using nextInt().Is it a bug [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
In this program, string variable fd doesn't wait taking input.
Can someone help me with this program.
i can get the input if i use the new scanner object though.
import java.util.Scanner;
public class Strmethod {
public static void main(String[] args)
{
String ch,fd;
int s,e;
Scanner sc=new Scanner(System.in);
System.out.print("Enter A String:");
ch=sc.nextLine();
System.out.println("String is "+ch);
System.out.println("Enter Two Numbers For Substring:");
s=sc.nextInt();
e=sc.nextInt();
System.out.println("Substring:"+ch.substring(s,e));
System.out.println("Enter a Word to search:");
fd=sc.nextLine();
System.out.println(ch.contains(f));
String jn=String.join("/","hello","g","u","y","s");
System.out.println(jn);
System.out.println(ch.startsWith("H"));
System.out.println(ch.startsWith("e"));
System.out.println("Length:"+ch.length());
String newstr=ch.replace("Hello","Hey");
System.out.println("String is "+ch);
}
}
The above picture shows the input in the form of a buffer your program is using.
Explanation:
When you first use the nextLine() function it reads the whole buffer up to \n character. Now the next buffer line starts and you have used nextInt() to read an integer 3 again nextInt() to read 6 now you have pressed enter i.e. \n character that is appended to the last of the buffer.
The current position of the buffer is that already contains the \n character so when you use the nextLine() method it consumes the \n character from the buffer and takes no input from the console.
Solution:
The solution is to use the nextLine() whenever using the last nextInt() or similar functions that don't read the full line.
The final program would be
...
System.out.println("Enter Two Numbers For Substring:");
s=sc.nextInt();
e=sc.nextInt();
sc.nextLine(); // <--- to read the last \n character from the buffer
System.out.println("Substring:" + ch.substring(s,e));
System.out.println("Enter a Word to search:");
fd=sc.nextLine();
...

some questions about java Scanner

enter image description here
}
Why does the code on line 6 have the same effect on line 8? Is there no distinction between the starting point of this while loop?
Also, you should follow this tips to use the Scanner properly:
Mixing any nextXXX method with nextLine from the Scanner class for user input, will not ask you for input again but instead result in an empty line read by nextLine.
To prevent this, when reading user input, always only use nextLine. If you need an int, do
int value = Integer.parseInt(scanner.nextLine());
instead of using nextInt.
Assume the following:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
int age = sc.nextInt();
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
When executing this code, you will be asked to enter an age, suppose you enter 20.
However, the code will not ask you to actually input a name and the output will be:
Hello , you are 20 years old.
The reason why is that when you hit the enter button, your actual input is
20\n
and not just 20. A call to nextInt will now consume the 20 and leave the newline symbol \n in the internal input buffer of System.in. The call to nextLine will now not lead to a new input, since there is still unread input left in System.in. So it will read the \n, leading to an empty input.
So every user input is not only a number, but a full line. As such, it makes much more sense to also use nextLine(), even if reading just an age. The corrected code which works as intended is:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
// Now nextLine, not nextInt anymore
int age = Integer.parseInt(sc.nextLine());
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
The nextXXX methods, such as nextInt can be useful when reading multi-input from a single line. For example when you enter 20 John in a single line.

Java : Scanner odd behaviour [duplicate]

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

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

Categories