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);
Related
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
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
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
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");
}
I am really a novice at Java but I'm giving it a shot with this program. This is a program to perform basic mathematical calculations, but with input from user.
import java.io.*;
import java.util.Scanner;
public class Math
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
int sa1, sa2, ss1, ss2, sm1, sm2, s;
boolean c = false;
double sd1, sd2;
while(c==false)
{
System.out.print("Do you want to: \n[1] Add. \n[2] Subtract. \n[3] Multiply. \n[4] Divide. \n[5] Exit \nPlease insert an option number below and press enter: ");
s = in.nextInt();
if (s==1)
{
System.out.print("You have chosen option 1 \nPlease enter your first number: ");
sa1 = in.nextInt();
System.out.print("Please enter your second number: ");
sa2 = in.nextInt();
System.out.print(sa1+ " + " +sa2+ " = " +(sa1+sa2));
}
if (s==2)
{
System.out.print("You have chosen option 2 \nPlease enter your first number: ");
ss1 = in.nextInt();
System.out.print("Please enter your second number: ");
ss2 = in.nextInt();
System.out.println(ss1+ " - " +ss2+ " = " +(ss1-ss2));
}
if (s==3)
{
System.out.print("You have chosen option 3 \nPlease enter your first number: ");
sm1 = in.nextInt();
System.out.print("Please enter your second number: ");
sm2 = in.nextInt();
System.out.println(sm1+ " x " +sm2+ " = " +(sm1*sm2));
}
if (s==4)
{
System.out.print("You have chosen option 4 \nPlease enter your first number: ");
sd1 = in.nextDouble();
System.out.print("Please enter your second number: ");
sd2 = in.nextDouble();
System.out.println(sd1+ " divided by " +sd2+ " = " +(sd1/sd2));
}
if(s>=6)
{
System.out.println("You have entered an incorrect option");
}
System.out.print("Would you like to try again? (Y/N): ");
String ans = in.nextLine();//prob with this line
char ans1 = ans.charAt(0);//or this line
if (ans1=='N' || ans1=='n')
{
c = true;
}
if(s==5)
{
c = true;
}
}
}
}
When I complile it I get an error: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Math.main(Math.java:58)
I've tried searching everywhere for an answer. Can anyone help me with this? It needs to be able to read either a 'Y' or a 'N' from the user.
You get the exception when you run it. Not when you compile it. And the error message says:
you're trying to get the char at index 0 of a string, but the String has no index 0. This exception happens at line 58 of Main.java.
A String which doesn't have a char at index 0 is an empty string.
This probably happens because the last thing you read from SYstem.in() is a number, and reading a number doesn't consume the end-of-line that comes after. Add a call to readLine() before reading Yes or No from the user. And don't assume that the user will do what you tell him to do. That's almost never true. Validate the inputs you read.