This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 8 years ago.
I'm trying to make a "Bank Account" and that requires the user to input the name, password, balance, and interest of that bank account. I use a sentinel controlledwhile loop to achieve this, but my sentinel does not work for some reason. Here's part of my code, if you could help me that would be great:
System.out.println("New Account: Enter name, type \"quit\" to exit. ");
String name = scan.nextLine();
while (!name.equals("quit")) {
System.out.println("Enter password: ");
String pass = scan.nextLine();
System.out.println("Enter balance (in pennies): ");
double bal = scan.nextDouble();
System.out.println("Enter interest: ");
double inter = scan.nextDouble();
BankAccount2 bankacc = new BankAccount2(name, pass, bal, inter);
accounts.add(bankacc);
System.out.println("Successful account creation! New Account: Enter name, type \"quit\" to exit. ");
name = scan.nextLine();
}
To clarify, the problem is that the first time when I enter "quit", before the loop starts, it works well and the loop does not begin. However, when I input a bank account, and it goes to "Enter name" all over again, when I type quit the loop does not stop.
I believe that the nextDouble() method does not read the next new line character. Check the documentation about this.
You might try calling nextLine() after calling nextDouble().
You can check the source of Scanner here. If you are stuck because of crappy javadoc or undocumented side effects I think it is always best if you check the code.
It seems that it is using a regex matcher which only matches a double pattern.
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();
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:
How to check that a string is parseable to a double? [duplicate]
(6 answers)
Closed 9 years ago.
I am making a program and cannot figure out how to make my scanner input only recognize numbers. Here is what I mean.
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
Distance = keyboard.nextDouble();
What can I put after the distance input in order to allow me to output some sort of message telling the user they didn't enter a number.
I thought maybe starting with something like
if (Distance != double)
System.out.print ("You did not enter a valid character, please enter again."
but that does not work. Any suggestions?
You need to use Scanner#hasNextDouble() method to test, whether there is a double value to read:
// While the next input is not a double value, repeat
while (!keyboard.hasNextDouble()) {
System.out.println("Please enter a valid numeric value");
keyboard.nextLine(); // Move Scanner past the current line
}
double distance = keyboard.nextDouble();
Also, the loop might go infinite, if the user keeps on passing wrong input. You can give him some max number of attempt to get it right, and then throw some exception, or display some message, and then do a System.exit(1);.
You can make this using a try cacth block, somethinh like:
System.out.print(" What is the distance in feet:" );
//ask the user to input variables
Distance = keyboard.nextDouble();
try
{
//you next code, considering a valid number
}catch (NumberFormatException ex)
{
//here u show a message ou another thing
}
Hope it helps ^^
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
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();