I am having a problem where my program is scanning for two different inputs at the same time.
import java.util.Scanner;
public class Person {
public static void main(String[] args){
Person p1 = new Person();
System.out.println("1: Add Person");
System.out.println("2: Delete Person");
System.out.println();
System.out.print("Please make a selection: ");
Scanner keyboard = new Scanner(System.in);
int selection = keyboard.nextInt();
switch(selection){
case 1:
System.out.print("Please enter name: ");
String name = keyboard.nextLine();
p1.addPerson(name);
break;
}
}
public Person(){
}
public void addPerson(String name){
int day, month, year;
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter date of birth in the format dd mm yyyy: ");
day = keyboard.nextInt();
month = keyboard.nextInt();
year = keyboard.nextInt();
}
}
This is the output:
1: Add Person
2: Delete Person
Please make a selection: 1
Please enter name: Please enter date of birth in the format dd mm yyyy:
The program does not wait for the name to be entered, how do i fix this?
The problem is when you do nextInt() it scans an integer, but not the new line character(\n), so when you call nextLine() it just consumes \n you typed when was doing selection and returns empty string.
Several ways to fix it:
First is to call nextLine() after nextInt. To fix your code you would do this:
int selection = keyboard.nextInt();
keyboard.nextLine();
Second option is to call nextLine() but when you need int wrap in in Integer.parseInt(). So, for example, your selection would look like:
int selection = Integer.parseInt(keyboard.nextLine());
Other option would be to use next() instead of nextLine, however, this approach wouldn't work if name contains spaces.
You should use keyboard.next()
From the java docs:
next(): Finds and returns the next complete token from this scanner.
This is what keyboard.nextLine() does:
nextLine(): Advances this scanner past the current line and returns the input that was skipped.
Related
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);
}
}
I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.
I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.
import java.io.IOException;
import java.util.Scanner;
public class ScannerTest {
static String name;
static Scanner in = new Scanner(System.in);
static int choice;
public static void main(String[] args) {
while(choice != 5){
System.out.print("\nEnter Choice :> ");
choice = in.nextInt();
if(choice == 1){
try{
printName();
}
catch(IOException e){
System.out.println("IO Exception");
}
}
}
}
private static void printName()throws IOException{
System.out.print("\nEnter name :> ");
name = in.next();
//name = in.nextLine();
if (name != null){
System.out.println(name);
}
}
}
Try this instead: add name = in.nextLine(); after choice = in.nextInt();.
Then try replacing name = in.next(); with name = in.nextLine();
Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the \n. We then consume the rest of the string with nextLine().
The second nextLine() is then used to get your string parameters.
The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine(), you will get whatever is between the number and the new line (usually nothing).
What you have to do, is call in.nextLine() just after reading the number to empty the buffer:
choice = in.nextInt();
if (in.hasNextLine())
in.nextLine();
before to call name = in.next(); do this in = new Scanner(System.in);
the object need rebuild itself because already has value.
good luck
Here is my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String question;
question = in.next();
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
When I try to write "how do you like school?" the answer is always "Que?" but it works fine as "howdoyoulikeschool?"
Should I define the input as something other than String?
in.next() will return space-delimited strings. Use in.nextLine() if you want to read the whole line. After reading the string, use question = question.replaceAll("\\s","") to remove spaces.
Since it's a long time and people keep suggesting to use Scanner#nextLine(), there's another chance that Scanner can take spaces included in input.
Class Scanner
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You can use Scanner#useDelimiter() to change the delimiter of Scanner to another pattern such as a line feed or something else.
Scanner in = new Scanner(System.in);
in.useDelimiter("\n"); // use LF as the delimiter
String question;
System.out.println("Please input question:");
question = in.next();
// TODO do something with your input such as removing spaces...
if (question.equalsIgnoreCase("howdoyoulikeschool?") )
/* it seems strings do not allow for spaces */
System.out.println("CLOSED!!");
else
System.out.println("Que?");
I found a very weird thing in Java today, so it goes like -
If you are inputting more than 1 thing from the user, say
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
So, it might look like if we run this program, it will ask for these 3 inputs and say our input values are 10, 2.5, "Welcome to java"
The program should print these 3 values as it is, as we have used nextLine() so it shouldn't ignore the text after spaces that we have entered in our variable s
But, the output that you will get is -
10
2.5
And that's it, it doesn't even prompt for the String input.
Now I was reading about it and to be very honest there are still some gaps in my understanding, all I could figure out was after taking the int input and then the double input when we press enter, it considers that as the prompt and ignores the nextLine().
So changing my code to something like this -
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
double d = sc.nextDouble();
sc.nextLine();
String s = sc.nextLine();
System.out.println(i);
System.out.println(d);
System.out.println(s);
does the job perfectly, so it is related to something like "\n" being stored in the keyboard buffer in the previous example which we can bypass using this.
Please if anybody knows help me with an explanation for this.
Instead of
Scanner in = new Scanner(System.in);
String question;
question = in.next();
Type in
Scanner in = new Scanner(System.in);
String question;
question = in.nextLine();
This should be able to take spaces as input.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}
// Week 3 Checkpoint1: Payroll Program Part 2
// Due May 04, 2012
// Created by: Kennith Adkins
import java.util.Scanner;
public class Assignment1
{
public static void main ( String[] args )
{
Scanner input = new Scanner(System.in);
// Variables
String employeeName = null;
int hours;
double rate;
double pay;
while ( employeeName != "stop")
{
// Request information from user
System.out.print ( "Employee Name: ");
employeeName = input.nextLine();
System.out.print ( "Hourly Rate: ");
rate = input.nextDouble();
System.out.print ( "Number of Hours worked this week: ");
hours = input.nextInt();
// Calculate pay
pay = rate * hours;
// Display information
System.out.printf ("%s will get paid $%.2f this week.\n", employeeName, pay);
}
}
}
When I run the program it runs fine. When it hits the loop and repeats, Employee Name: and Hourly Rate seem to bunch up. Also how would I get it to immediately stop after typing stop as employee Name?
As this appears to be a homework question I'll point you in a learning direction.
So for the employee name question I will redirect you to How do I compare strings in Java?
The scrunching issue is because when you reenter the loop and call scanner(input).nextLine it ends up actually reading the input text that it had not seen yet. So one option is to switch to something else lick a BufferedReader or move the scanner deceleration down in to the loop.
More research
I haven't worked much with the scanner class and after seeing this I was somewhat confused. The issue is actually the nextInt and nextDouble. They dont claim the return charter and as such when you call next line next time it is picking up the leftover return character.
So my option of reseting the scanner when reentering works in this specific case but you should either use 2 scanners or move off of scanners.
Scanner txtinput = new Scanner(System.in);
Scanner numberinput = new Scanner(System.in);
I'd like to use the snippet of code below to allow a user to enter four values at once separated by spaces, in which case they would be captured separately and assigned to variables. Alternatively, the user could enter one value at a time while waiting for prompts between each value. If the if(in.hasNext()) worked like I had hoped, this solution would have been easily doable with the code below, but I have learned that hasNext is apparently always evaluating to TRUE, even when there is no additional token in the stream, so the program blocks and waits for input. Is there a way to adjust this code to get the desired results? (month, day, and year are strings that get parsed to integers later in the program.) Thanks
Scanner in = new Scanner(System.in);
System.out.println("Please enter your first name, last name, or full name:");
traveler = in.nextLine();
System.out.println("Please enter your weight, birth month, birth day of month, and birth year as numbers.\nYou may enter all the numbers at once -- right now -- or you may enter them one at a time as the prompts appear.\nOr, you may also enter them in any combination at any time, so long as weight (at least) is entered now and the remaining \nthree numbers are eventually entered in their correct order:");
pounds = in.nextInt();
if (in.hasNext()) {
month = in.next();
} else {
System.out.println("Please enter your birth month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth month:");
month = in.next();
}
if (in.hasNext()) {
day = in.next();
} else {
System.out.println("Please enter your birth day of month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth day of month:");
day = in.next();
}
if (in.hasNext()) {
year = in.next();
} else {
System.out.println("If you've made it this far, then please just enter your birth year:");
year = in.next();
}
Read a line at a time, then call split(" ") to determine how many and which values the user entered.
There is a InputStream.available() method that returns how many characters can be read without blocking; however, that does not determine whether there is a complete number or line. The Scanner class's documentation explicitly says that hasNext can block, though.