This question already exists:
Scanner issue when using nextLine after nextXXX [duplicate]
Closed 9 years ago.
Here is the skeleton of some basic code I am writing to make a simple game:
Scanner in = new Scanner(System.in);
String name;
String playing;
int age;
do {
System.out.println("Enter your name");
name = in.nextLine();
System.out.println("Enter your age");
age = in.nextInt();
System.out.println("Play again?");
playing = in.nextLine();
} while (true);
The code does not work as expected, for example, here is the expected functioning of the code:
Enter your name
John
Enter your age
20
Play again?
Yes
Enter your name
Bill
...
However, there is an issue with reading the Play again line, this is the actual output:
Enter your name
John
Enter your age
20
Play again?
Enter your name
As you can see "Enter your name" is being displayed again before "Play again?" is able to accept input. When debugging the playing variable is set to "", so there is no input that I can see and I cannot figure out what is being consumed.
Any help would be appreciated, thanks!
nextInt() doesn't consume the end-of-line, even if the int is the only thing in there.
Add another nextLine() after reading the int, and either discard its value completely, or check that it is empty if you want to prevent people from entering anything but an int.
The problem is that after calling nextInt() there is still a '\n' in the buffer and so that is what is passed. use in.next() instead of in.nextLine().
Use next() method in Scanner class instead of nextLine() method.
Scanner in = new Scanner(System.in);
String name;
String playing;
int age;
do {
System.out.println("Enter your name");
name = in.next();
System.out.println("Enter your age");
age = in.nextInt();
System.out.println("Play again?");
playing = in.next();
} while (true);
for more information refer Java Documentation for Scanner class
Output :
Enter your name
Kanishka
Enter your age
23
Play again?
Yes
Enter your name
....
You should use the following code for the next line reading.
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
And for reading the line you should write
scanner.next();
Related
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 1 year ago.
I'm new to java and I wrote this code
import java.util.Scanner;
public class GamingJava {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String Name;
int password;
String yEs;
System.out.print("hello sir what is your name? ");
Name = input.nextLine();
System.out.print("what is your password? ");
password = input.nextInt();
System.out.println("your name was "+Name+" and your password was "+password);
System.out.print("are you sure? ");
yEs = input.nextLine();
System.out.println(yEs);
}
}
It only ask the name and the password, but Java doesn't ask the last one how did that happen?
It asks for the input and immediately takes it as an empty string i.e. "".
Root Cause : The issue is because of the nextLine() method. Since while providing an input, user has to press the Enter key, the cursor/prompt on the console moves to next line. This line is taken as an empty line by the nextLine() method.
Solution : You must use the next() method as it looks out for the presence of space character for taking the input.
FYR the following line of code
yEs = input.nextLine();
should be changed to
yEs = input.next();
I'm making a java program that has to store data using classes and objects, My question is how do input characters like a name ( billy ) into my code.
Here is the class i did.
class bank
{
int AccountID;
int HolderName;
double AccountBalance;
}
And i'm assigning here
angel.AccountID = 7532;
angel.HolderName = 753; // angel
angel.AccountBalance = angelbalance;
I know that i can input integers using the following code
System.out.println("Set Balance for Angel: ");
int angelbalance = sc.nextInt();
My question is how do i input text/characters in a way (scanner) does with integer
Sorry for the bad explanation.
Do you mean getting the name input using the Scanner object? Because you've imported java.util.Scanner, you can do:
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
This will read the next line.
You can use (JOptionPane.showInputDialog) and it is easy to use if you want input from user
String name= JOptionPane.showInputDialog("Enter your name: "));
You need to either call the Scanner.nextLine() method or the Scanner.next() method to store String input such as a name like "Billy". Here is an example below:
//You can use the Scanner.next() method or the Scanner.nextLine() method to store Strings
Scanner scan = new Scanner(System.in);
System.out.println("Enter a name: ");
String billy = scan.next();
System.out.println("You entered: " + billy);
And here is your output:
Enter a name:
Billy
You entered: Billy
I'd check out the Scanner documentation here: https://docs.oracle.com/javase/8/docs/api/java/util/class-use/Scanner.html
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am learning Java and I was trying an input program. When I tried to input an integer and string using instance to Scanner class , there is an error by which I can't input string. When I input string first and int after, it works fine. When I use a different object to Scanner class it also works fine. But what's the problem in this method when I try to input int first and string next using same instance to Scanner class?
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :" );
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
String name= input.nextLine();
System.out.println("Your Next is : " + name);
}
}
nextInt() doesn't wait for the end of the line - it waits for the end of the token, which is any whitespace, by default. So for example, if you type in "27 Jon" on the first line with your current code, you'll get a value of 27 for ip and Jon for name.
If you actually want to consumer a complete line, you might be best off calling input.nextLine() for the number input as well, and then use Integer.parseInt to parse the line. Aside from anything else, that represents what you actually want to do - enter two lines of text, and parse the first as a number.
Personally I'm not a big fan of Scanner - it has a lot of gotchas like this. I'm sure it's fine when it's being used in exactly the way the designers intended, but it's not always easy to tell what that is.
If you call input.nextInt(); the scanner reads the number from the input, but leaves the line separator there. That means, if you call input.nextLine(); next, it reads everything till the next line separator. And this is in this case only the line separator itself.
You can fix that in two ways.
Way 1:
int ip = Integer.parseInt(input.nextLine());
// output
String name= input.nextLine();
Ways 2:
int ip = input.nextInt();
// output
input.nextLine();
String name= input.nextLine();
This one working, Anyway if you want to save IP address it must be String.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Scanner input2=new Scanner(System.in);
System.out.println("Enter your number :");
int ip = input.nextInt();
System.out.println("Your Number is : " + ip);
System.out.println("Enter Your Name : ");
input.nextLine();
String name = input.nextLine();
System.out.println("Your Next is : " + name);
}
}
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I was writing my first, well second if you count hello world, program and ran into a small issue.
My code:
import java.util.*;
class test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("What is your name: ");
String name = scan.nextLine();
System.out.print("What is your favorite number: ");
int favoriteNumber = scan.nextInt();
System.out.print("What is your favorite game: ");
String game = scan.nextLine();
}
}
So it scans in name and favoriteNumber but the program ends before asking the user to enter a favorite game. Essentially the user can only enter text twice instead of three times like I would like.
Just a guess: scan.nextInt() does not consume the trailing newline character after the user presses enter. The subsequent call to scan.nextLine() then finds a newline character waiting.
Try switching out int favoriteNumber = scan.nextInt(); for String favoriteNumber = scan.nextLine(); to see if that fixes the issue. If it does, my hypothesis is correct.
If that is the case, then you should probably use Integer.parseInt to convert this string into an integer. The problem here is effectively that you really want to collect 3 lines of input, where a line is defined as "any sequence of characters ending with a newline". Your program is currently written to request a line, an int, then a line, rather than "3 lines of input, one of which contains an int".
an exception must be thrown in here scan.nextInt();
Check whether you entered a proper int
I have been trying all weekend to find a way to get my program to answer a question using a sting with a scanner class. For example I need to get my program to answer a question like
Who is on the 5 dollar bill?
Input would be Lincoln and other inputs would be invalid
the question will have 3 choices so the logic has to work.
Can you point me in the right direction on how to get this to work in Java? I want to understand the material but I have really tried all weekend.
If I understood your question properly, then this should point you in the right direction:
Import the Scanner:
import java.util.Scanner;
Then, here is the method you'd want to call:
public void myScanner () {
Scanner scan = new Scanner(System.in); //Creates a new scanner
System.out.println("Who is on the 5 dollar bill?"); //Asks question
String input = scan.nextLine(); //Waits for input
if (input.equalsIgnoreCase("Lincoln")) { //If the input is Lincoln (or any case variant of Lincoln)
System.out.println("Correct!");
}
else { //If the input is anything else
System.out.println("Incorrect!");
}
}
If you don't want to encode all the actual word solutions (like "Lincoln") you can also just ask the user to pick a number/letter solution since you only have 3.
Scanner input = new Scanner(System.in);
System.out.println("Who is on the 5 dollar bill? 1. Lincoln 2. Somebody 3. Someone");
String userChoice = scan.nextInt(); //get a number from user
if(userChoice == 1)
System.out.println("Correct answer!");
else
System.out.println("Wrong answer!");
This would make it easy to keep track of the answer key.
Scanner input = new Scanner(System.in);
System.out.println("Who is on the 5 dollar bill?");
String userinput = input.nextLine(); //get a name from user
if(userinput.equalsIgnoreCase("Lincoln"))
{ System.out.println("Answer is correct");}
else
{ System.out.println("Answer is wrong");}
}}