nextLine printing out 2 at a time? [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 5 years ago.
So everything compiles fine but when I run it the line asking for city and the line asking for zip both print out at the same time. I need them to print individually so the user can answer.
import java.util.Scanner;
public class PersonalInfo
{
public static void main(String[] args)
{
String name, city, state, major;
int zip, phone, address;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name: ");
name = scanner.nextLine();
System.out.println("please enter your address number: ");
address = scanner.nextInt();
System.out.println("Please enter the name of the city you live in: ");
city = scanner.nextLine();
System.out.println("Please enter your zip code: ");
zip = scanner.nextInt();
System.out.println("Please enter the name of the state you live in: ");
state = scanner.nextLine();
System.out.println("Please enter your phone number(format ##########): ");
phone = scanner.nextInt();
System.out.println("Please enter your college major: ");
major = scanner.nextLine();
System.out.println(name + "\n" + address + "," + city + "," + state +
"," + zip + "\n" + phone + "\n" + major);
}
}

The only method that consume newline of the input is nextLine(), so if you use nextInt() and then you want to capture anything else you have to call a nextLine() after you call nextInt().
For example:
System.out.println("please enter your address number: ");
address = scanner.nextInt();
scanner.nextLine();
System.out.println("Please enter the name of the city you live in: ");
city = scanner.nextLine();
Output:
please enter your address number:
567
Please enter the name of the city you live in:
Puerto Montt

Related

Difference between two codes and InputMismatchException

I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:
1st one with the Exception Error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName, completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name and your age: ");
completeName = sc.next();
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your complete name and your age:
Peter Henrik 22
(InputMismatchException)
2nd one with no error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + firstName + " " + lastName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your age:
22
Your complete name is: Peter Henrik
Your age is: 22
Your first code throws InputMismatchException because sc.next() reads the first complete token ("Peter") up to the whitespace (since whitespace is the default delimiter for Scanner in Java), thus after that, the sc.nextInt() method will read "Henrik" which is a String unlike your expectation to read the age (22).
Here's what you can do instead in order to read the complete name of the user as well as the age [CONDITION: You'll have to enter age in a new line]:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName,completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name: ");
completeName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
PS: An alternate solution can be to read the complete name and the age in a single line as you did and then split up the tokens using the String split() method in Java.
Having a look at the Javadoc of Scanner#next() will tell you the following:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter for the Scanner is a whitespace.
Knowing this, you provide the following input
Peter Henrik 22
and try to read this input via the following
completeName = sc.next();
age = sc.nextInt();
The call to sc.next() will read the first complete token up to the whitespace, which is "Peter".
So Henrik 22 is still available in the Scanner buffer.
Therefore sc.nextInt() will read Henrik and try to parse it to an int hence the InputMismatchException.
To read both tokens to get the complete name, simply change
completeName = sc.next();
to
completeName = sc.next() + " " + sc.next();
However, names don't always consist of only two parts. Since there could be names that more than two single tokens, you should / could do it like the following (provided you still want to enter the complete name and age in one line):
String line = sc.nextLine(); // read the whole line
// everything up to the last token is the name
completeName = line.substring(0, line.lastIndexOf(" "));
// last token is the age
age = line.substring(line.lastIndexOf(" ") + 1);

Two print statements, but only one displays a user input string [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 2 years ago.
With this code, I'm looking to get 2 foods from the user. The print statement with food1 prints and displays the string the user entered correctly in the console.
With the print statement for food2, it will print the statement but the string that the user input will not display along with it.
I've tried using print/println neither change anything.
for(x=1; x <= 2; x++)
System.out.print("Enter nationality of the food: ");
Nation = sc.nextLine();
System.out.print("Enter your first food: ");
food1 = sc.nextLine();
System.out.print("Enter food price: ");
value1 = sc.nextDouble();
System.out.print("Enter your second food choice: ");
food2 = sc.nextLine();
sc.next();
System.out.print("Enter food price: ");
value2 = sc.nextDouble();
total = (value1 + value2);
System.out.println("Your food nationality: " + Nation);
System.out.printf("Your total price is: %.2f\n", total);
System.out.print("Would you like to list your items? (1 For Yes/2 For No)");
choice = sc.nextInt();
while( choice == 1)
System.out.println("Your first food: " + food1); // This one displays correctly in the console
System.out.println("Your second food: " + food2); // This one does not display the string that the user inputted in the console
choice++;
sc.nextLine();
sc.nextDouble() does not take in the entire line, only the next decimal value. Therefore you will need to read in that line before reading in food2.
System.out.print("Enter your first food: ");
food1 = sc.nextLine();
System.out.print("Enter food price: ");
value1 = sc.nextDouble();
sc.nextLine(); // add this line
System.out.print("Enter your second food choice: ");
food2 = sc.nextLine();
sc.next(); // I am not sure what you are doing here. If I understand your code correctly, you can delete this
System.out.print("Enter food price: ");
value2 = sc.nextDouble();
sc.nextLine(); // add this line

java prompt + get number before get a string contain any space (one or more)

I need get a number from prompt, and juste after I need get a String list from prompt. I have a problem. Is it OK if the 1st question ask a string with nextLine() see this post.
Java code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console result:
Enter a number:
2
Enter a name list:
Enter last name:
1st response is 2 + enter
but juste after 2 + enter, the program display Enter a name list:
Enter last name:
I would use input.next() instead of input.nextLine() as next blocks for user input while nextLine moves the scanner past the current line and it buffers all the inputs until it finds a line separator.
or use nextLine() after nextInt to consume the linefeed which is left by nextInt
Solution add input.nextLine(); juste after int num = input.nextInt();.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
input.nextLine();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console:
Enter a number:
2
Enter a name list:
aa bb cc
Enter last name:
dd
2 * aa bb cc ** dd

how do I make the program take the input before displaying results

I'm new to java and I made this program, the problem I'm asking the user to input their age and name then the program should use the input to print the statement. however the when I type the age then press enter the program executes all the statements without waiting for me to enter my name.. how can I fix this?
Scanner input = new Scanner(System.in);
int age;
String name;
System.out.println("Please enter your age ");
age = input.nextInt();
System.out.println("and now enter your name");
name = input.nextLine();
System.out.println("Your name is " +name + " and you're " +age + "years old");
You can use nextLine() for both:
System.out.println("Please enter your age ");
age = Integer.parseInt(input.nextLine());
System.out.println("and now enter your name");
name = input.nextLine();
The problem is that when you hit Enter after you input the age, the resulting newline is interpreted as the end of the input for the following nextLine().
You could also use next() instead of nextLine(), but then John Doe would be interpreted as just John because next() uses whitespace as a separator.
Use next() instead of nextLine() at name variable.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age;
String name;
System.out.println("Please enter your age ");
age = input.nextInt();
System.out.println("and now enter your name");
name = input.next();
System.out.println("Your name is " +name + " and you're " +age + " years old");
}

Why is this program not running correctly?

I have the following code:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//System.out.println("Enter quantity:");
//int quantity = input.nextInt();
//System.out.println("You entered: " + quantity);
//System.out.println("Enter price: ");
//double price = input.nextDouble();
//System.out.println("You entered: " + price);
System.out.println("Enter city: ");
String city = input.nextLine();
System.out.println("You entered: " + city);
System.out.println("Enter state code: ");
String state = input.next();
System.out.println("You entered: " + state);
}
}
When I run the program with the middle section commented out like this, it works correctly. But when I uncomment it, it messes up the last block by printing the following lines simultaneously:
Enter city:
You entered:
Enter state code:
Why is this happening, and how can I fix it?
You typed something like this:
12<enter>1.3<enter>AZ
right?
When you call nextInt, it reads the next integer. So it reads "12" and what is left is:
<enter>1.3<enter>AZ<enter>
Now you call nextDouble. It skips past the first <enter> and reads "1.3" (a double). What is left is:
<enter>AZ<enter>
Now you call nextLine, which reads until the next <enter>. Oh look, you already pressed <enter>! So it reads the <enter> and returns a blank line. What is left is:
AZ<enter>
Now you call nextLine again, which reads until the next <enter>. It reads AZ<enter> and returns "AZ".
This is a quirk of how Scanners and streams work. The usual fix is to call nextLine immediately after nextInt and nextDouble, and ignore the result. Something like:
System.out.println("Enter quantity: ");
int quantity = input.nextInt();
input.nextLine(); // ignore newline
System.out.println("You entered: " + quantity);
System.out.println("Enter price: ");
double price = input.nextDouble();
input.nextLine(); // ignore newline
System.out.println("You entered: " + price);
input.nextDouble();
does not consume the line, insert a line:input.nextLine();
right after the commented block, don't assign it to any variable.
use ScnObj.next() instead of ScnObj.nextLine();
System.out.println("Enter price: ");
double price = ScnObj.nextDouble();
System.out.println("You entered: " + price);
System.out.println("Enter city: ");
String city = ScnObj.next();
System.out.println("You entered: " + city);
System.out.println("Enter state code: ");
String state = ScnObj.next();
System.out.println("You entered: " + state);

Categories