This question already has answers here:
Scanner issue when using nextLine after nextXXX [duplicate]
user input string and integers in Java [duplicate]
(3 answers)
Closed 8 years ago.
int id;
float grade;
String name;
Scanner z= new Scanner(System.in);
System.out.println("Give the id:\n");
id=z.nextInt();
System.out.println("your id is :"+id+"\n");
System.out.println("Give the name:");
name=z.nextLine();
System.out.println("your name is :"+name);
System.out.println("Give the grade:\n");
grade=z.nextFloat();
The problem goes like this.It inputs the integer but when it comes to the String, it prints "Give the name" but it doesn't waits until I type something, it skips to the next instruction.
Why's that?
You have used name=z.nextLine(), hence such behavior, Replace it with name=z.next(). Below is the edited code:
int id;
float grade;
String name;
Scanner z= new Scanner(System.in);
System.out.println("Give the id:\n");
id=z.nextInt();
System.out.println("your id is :"+id+"\n");
System.out.println("Give the name:");
name=z.next();
System.out.println("your name is :"+name);
System.out.println("Give the grade:\n");
grade=z.nextFloat();
When you read int value using nextInt, it reads only the int value, it skips the new line character. The latter will be read in the next nextLine causing it to skip the "real" input.
You can fix this by adding another nextLine before the "real" nextLine, it'll swallow the '\n' that you don't want to read.
Important note: Don't use int to store ID value! Use String instead!
The problem is with the input.nextInt() command it only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine()
id = z.nextInt();
System.out.println ("your id is :"+id+"\n");
z.nextLine ();// add this line between the next line read
System.out.println("Give the name:");
or
id = Integer.parseInt(z.nextLine());
System.out.println ("your id is :"+id+"\n");
System.out.println("Give the name:");
Related
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.
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
i was practicing scanner usage and syntax and below is the code i wrote, where I am trying to take 4 inputs from the user :
Scanner s= new Scanner(System.in);
int a = s.nextInt();// taking an integer as input, it works fine.
String b = s.nextLine();//was supposed to take a string input, but not working
String c=s.nextLine();//takes a string as input from user
String d=s.nextLine();//takes another string as input from user
System.out.println("integer entered: "+a);
System.out.println("first string entered: "+b);
System.out.println("second string entered: "+c);
System.out.println("third string entered: "+d);
but the user is able to give only 3 inputs, the first integer and other two string inputs and by printing the values of these 4 variables, it is clear that input for first string String b is skipped.I then tried to rearrange the sequence in which the input was taken, i.e,
String b = s.nextLine();//takes a string input
int a = s.nextInt();// taking an integer as input
String c=s.nextLine();//was supposed to take a string as input from user
String d=s.nextLine();//takes another string as input from user
in this case, the input for the second string String cis skipped.
So, is it because of the integer input that skips the next string input?
This is a common question.
Fixed code
Scanner s= new Scanner(System.in);
int a = s.nextInt();
s.nextLine();
System.out.print("Enter a string: ");
String b = s.nextLine();
System.out.print("Enter another string: ");
String c=s.nextLine();
System.out.print("Enter one more string: ");
String d=s.nextLine();
System.out.println(a+"\n"+b+d+c);
Ref:
Scanner is skipping nextLine() after using next() or nextFoo()?
This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
I am using a do-while loop that loops based on the input of the user as a 'Y' or 'N'. If the user chooses to continue by pressing 'Y' or 1 (for simplicity), on the second iteration it skips the first input in the same loop.
do{
System.out.println("Enter the location: ");
cartItem.purchaseLocation = input.nextLine(); // This input is skipped on second iteration
System.out.println("Enter the product description: ");
cartItem.productDescription = input.nextLine();
System.out.println("Enter the price of the item: ");
cartItem.productPrice = input.nextDouble();
System.out.println("Enter the quantity: ");
cartItem.quantity = input.nextInt();
cartList.add(cartItem);
System.out.println("Do you want to add more items ? y = 1 / n = 0: ");
exitVar = input.nextInt();
}while(exitVar!=0); // Repeat till no more items need to be added in the cart
So when the user presses input 0 to repeat the procedure, the line
cartItem.purchaseLocation = input.nextLine();
which is the very first input in the loop will be skipped. Any suggestions what might be wrong here ?
same question as Skipping nextLine() after use nextInt()
input.nextInt() does not read a line, when your input is "1\n", it read "1" and leaves "\n" to the next read, which is
cartItem.purchaseLocation = input.nextLine();
Instead of using input.nextLine() use input.next() assuming input is a Scanner object.
If it is not, please clarify what input is.
I have the following Java code:
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter your name>>");
String name = input.next();
System.out.println("Enter your year of birth>>");
int age = input.nextInt();
System.out.println("Name: " + name);
System.out.println("Year of Birth: " + age);
System.out.println("Age: " + (2012 - age));
} catch (InputMismatchException err) {
System.out.println("Not a number");
}
When I enter a name with a space (e.g. "James Peterson"), I get the next line output correctly (Enter your year of birth) and then an InputMismatchException immediately. The code works with a single name without spaces. Is there something I'm missing?
System.out.println("Enter your name>>");
String name = input.next();
System.out.println("Enter your year of birth>>");
int age = input.nextInt();
Scanner, breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
When you enter "James Peterson", Scanner#next() takes "James" as a token and assigns it to String name and then you do a Scanner#nextInt() which takes "Peterson" as the next token, but it is not something which can be cast to int and hence the InputMismatchException asnextInt() will throw an InputMismatchException if the next token does not match the Integer regular expression, or is out of range.
Actually the problem in your code has been clearly pointed out. In your case, there are two typical ways to achieve that:
One
Using useDelimiter method to delimite the input and after each input, you need to hit the Enter.
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
In your case, you need to
Scanner sc = new Scanner(System.in);
sc.setDelimiter("\\n");
// hit the "Enter" after each input for the field;
Two
Also you can achieve the same result using readLine
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.
In this way, you can do
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name>>");
String name = sc.nextLine();
...
System.out.println("Enter your year of birth>>");
int age = sc.nextInt();
P.S.
Actually you can achieve it in a more restrictive way, controlling the pattern using next(Pattern pattern), if you need it.
int age = sc.next(Pattern.compile("\\d+{1,3}"));
In this case, if the input DOES NOT match the pattern, it will throw InputMismatchException as you were trying to nextInt while the input is a string.
When I enter a name with a space (e.g. "James Peterson"), I get the next line output correctly (Enter your year of birth>>) and then an InputMismatchException immediately.
I am having trouble reading in strings from the user after reading in an int. Essentially I have to get an int from the user and then several strings. I can successfully get the user's int. However, when I begin asking for strings (author, subject, etc...), my scanner "skips" over the first string input.
For example, my output looks like this:
Enter your choice:
2
Enter author:
Enter subject:
subject
As you can see, the user is never able to enter the author, and my scanner stores null into the author string.
Here is the code that produces the above output:
String author;
String subject;
int choice;
Scanner input = new Scanner(System.in);
System.out.println("Enter choice:");
choice = input.nextInt();
System.out.println("Enter author:");
author = input.nextLine();
System.out.println("Enter subject:");
subject = input.nextLine();
Any help would be greatly appreciated. Thank you!
-Preston Donovan
The problem is that when you use readLine it reads from the last read token to the end of the current line containing that token. It does not automatically move to the next line and then read the entire line.
Either use readLine consistently and parse the strings to integers where appropriate, or add an extra call to readLine:
System.out.println("Enter choice:");
choice = input.nextInt();
input.nextLine(); // Discard the rest of the line.
System.out.println("Enter author:");
author = input.nextLine();
This works perfectly.
Although while making previous programs like the one below it was not required. Can anyone explain this?
import java.util.Scanner;
public class Average Marks {
public static void main(String[] args) {
Scanner s = new Scanner ( System.in);
System.out.print("Enter your name: ");
String name=s.next();
System.out.print("Enter marks in three subjects: ");
int marks1=s.nextInt();
int marks2=s.nextInt();
int marks3=s.nextInt();
double average = ( marks1+marks2+marks3)/3.0;
System.out.println("\nName: "+name);
System.out.println("Average: "+average);