This question already exists:
Closed 10 years ago.
Possible Duplicate:
Scanner issue when using nextLine after nextInt
I am trying create a program where it lets the user inputs values into an array using scanner.
However, when the program asks for the student's next of kin, it doesn't let the user to input anything and straight away ends the program.
Below is the code that I have done:
if(index!=-1)
{
Function.print("Enter full name: ");
stdName = input.nextLine();
Function.print("Enter student no.: ");
stdNo = input.nextLine();
Function.print("Enter age: ");
stdAge = input.nextInt();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();
Student newStd = new Student(stdName, stdNo, stdAge, stdKin);
stdDetails[index] = newStd;
}
I have tried using next(); but it will only just take the first word of the user input which is not what I wanted. Is there anyway to solve this problem?
The problem occurs as you hit the enter key, which is a newline \n character. nextInt() consumes only the integer, but it skips the newline \n. To get around this problem, you may need to add an additional input.nextLine() after you read the int, which can consume the \n.
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();.
// rest of the code
The problem is with the input.nextInt() this function only reads the int value. So when you continue reading with input.nextLine() you receive the "\n" Enter key. So to skip this you have to add the input.nextLine().
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine();
Function.print("Enter next of kin: ");
stdKin = input.nextLine();
Why next() is not working..?
next() returns next token , and nextLine() returns NextLine. It good if we know difference. A token is a string of non blank characters surrounded by white spaces.
From Doc
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
Make input.nextLine(); call after input.nextInt(); which reads till end of line.
Example:
Function.print("Enter age: ");
stdAge = input.nextInt();
input.nextLine(); //Call nextLine
Function.print("Enter next of kin: ");
stdKin = input.nextLine();
Related
When I run my program instead of reading the string and storing it in tempAddress my program simply prints the next line before I enter input. Using next works for the first two because I am only using one word but the third one encompasses multiple words so need something else and through my research I found nextLine() was the answer but I am not able to get it to work as others have, thanks in advance.
System.out.println("Enter Employee First Name: ");
String tempFirstName = input.next();
employeesArray[i].setFirstName(tempFirstName);
System.out.println("Enter Employee Last Name: ");
String tempLastName = input.next();
employeesArray[i].setLastName(tempLastName);
System.out.println("Enter Employee Address: ");
String tempAddress = input.nextLine();
employeesArray[i].setAddress(tempAddress);
System.out.println("Enter Employee Title: ");
String tempTitle = input.next();
employeesArray[i].setTitle(tempTitle);
Basically Scanner tokenizes the input by default using whitespace. Using next() method of scanner returns the first token before the space and the pointer stays there. Using nextLine() returns the whole line and then moves the pointer to the next line.
The reason your nextLine() was not behaving fine was because, your previous input for employee last name using next() cause the pointer to stay in the line hence, when you reach the point to take the employee address using nextLine(), the pointer returns remainder of the previous input next() which was obviously empty (when supplied one word as input to next()). Assume you entered two words separated by space for last name, the next() will store the first word in last name field and pointer waits after first token before second token and as soon as you reach nextLine() pointer returns the second token and moves to new line.
The solution is to execute nextLine() after reading the input for last name to make sure that your pointer is in new line waiting for input for address.
I updated my code by inserting a input.nextLine() there to make sure that scanner input is consumed and pointer is moved to the next line.
System.out.println("Enter Employee First Name: ");
String tempFirstName = input.next();
employeesArray[i].setFirstName(tempFirstName);
System.out.println("Enter Employee Last Name: ");
String tempLastName = input.next();
employeesArray[i].setLastName(tempLastName);
//feed this to move the scanner to next line
input.nextLine();
System.out.println("Enter Employee Address: ");
String tempAddress = input.nextLine();
employeesArray[i].setAddress(tempAddress);
System.out.println("Enter Employee Title: ");
String tempTitle = input.next();
employeesArray[i].setTitle(tempTitle);
When you have input.next(), it reads the input, but not the newline character, it leaves it in the input stream. input.nextLine() ends with a newline character. So when input.nextLine() is executed, it stops without taking any input because it already got the newline (\n) char from the input stream.
Solution: read the newline before you execute inupt.nextLine():
System.out.println("Enter Employee Address: ");
input.next();//read the newline char - and don't store it, we don't need it.
String tempAddress = input.nextLine();
see also: https://stackoverflow.com/a/13102066/3013996
This question already has an answer here:
Trouble using nextInt and nextLine()
(1 answer)
Closed 8 years ago.
System.out.println("Enter UPC for an item you want, enter -1 when done");
do {
System.out.print("\nEnter a UPC ");
targetUPC = keyboard.nextLine();
RetailItem temporary = new RetailItem("Default", 0, 0, targetUPC);
if(itemList.indexOf(temporary) > -1) {
RetailItem itemIndex = itemList.get(itemList.indexOf(temporary));
System.out.println("\n" + itemIndex);
System.out.print("How many would you like? ");
numOfItems = keyboard.nextInt();
itemIndex.setInStock(itemIndex.getInStock() - numOfItems);
totalCost = numOfItems * itemIndex.getPrice();
}
if(itemList.indexOf(temporary) == -1 && !targetUPC.equals("0")) {
System.out.print(targetUPC + " not found.\n");
}
Here's some output for it:
Enter UPC for an item you want, enter -1 when done
Enter a UPC: 999
999 not found.
Enter a UPC: 61835
Description: Corn Crisps
Price: $9.45
Number in stock: 35
UPC: 61835
How many would you like? 5
Enter a UPC not found. //Why am I getting this?
Enter a UPC 0
Total cost: $47.25
I've been going through it in my head and can't figure it out
You are mixing nextInt() which leaves trailing newline, with nextLine() in a loop. Read the trailing newline like,
numOfItems = keyboard.nextInt();
keyboard.nextLine();
Or consume the entire line in the first place like,
numOfItems = Integer.parseInt(keyboard.nextLine().trim());
When the user enters a line of input for numOfItems, nextInt() does not consume that line. So when you get back to the start of the loop and call targetUPC = keyboard.nextLine();, you get the remains of the line already entered. Put in a call to nextLine(); after you read numOfItems to consume the rest of the input ready for the next loop.
nextInt() will leave an unread newline in the input buffer.
This newline is subsequently processed by the nextLine() call, which then returns an empty string, which gets assigned to targetUPC and there is presumably no matching RetailItem…
I am now having a difficult time fixing this problem.
So, I have this code snippet here which asks 3 input from the user.
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.next();
System.out.print("Enter account PIN: ");
pin = input.next();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;
But everytime I run it, it always skips the input for the String "name", I tried using input.next(); on it and it works but then it will now skip the input for String "accnum".
EDIT: It also just happens if the input from "name" has a space on it, for example : John Doe.
Am I missing something here?
The nextLine() gobbles the newline character produced by the next() of account pin (when you hit enter). So, it won't ask for name. Add input.nextLine() after pin = input.next(); and try
Try This. i think problem with next(). since next reads input as tokens with default delimiter(i think space is the default delimiter).:
case 0:
String accnum,pin,name;
System.out.print("Enter account name: ");
name = input.nextLine();
System.out.print("Enter account number: ");
accnum = input.nextLine();
System.out.print("Enter account PIN: ");
pin = input.nextLine();
atm.set_accinfos(name,accnum,pin);
//System.out.print(atm.return_acc() + "\t" + atm.return_pin() + "\n");
break;
If you're using input anywhere before this block of code, then you need to be sure to call nextLine earlier on.
If you use next instead, then your input stream will still contain a new line character (\n). Thus, when you start this block of code with nextLine, that call will take the previous \n and not the name which was just entered.
In general, if your Scanner is reading System.in, then you should use nextLine everywhere. next, nextInt, and the other next methods are meant for more predictable data.
Okay, thats for the help everyone, I managed to fix it by adding "input.nextLine();" before "name = input.nextLine();"
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 28 days ago.
So I instantiate the Scanner scan a lot earlier but it skips right over my second scan.nextLine() after scan.nextInt(). I don't understand why it skips over it?
System.out.println("Something: ");
String name = scan.nextLine();
System.out.println("Something?: ");
int number = scan.nextInt();
System.out.println("Something?: ");
String insurer = scan.nextLine();
System.out.println("Something?: ");
String another = scan.nextLine();
because when you enter a number
int number = scan.nextInt();
you enter some number and hit enter, it only accepts number and keeps new line character in buffer
so nextLine() will just see the terminator character and it will assume that it is blank String as input, to fix it add one scan.nextLine() after you process int
for example:
System.out.println("Something?: ");
int number = scan.nextInt();
scan.nextLine(); // <--
When you call int number = scan.nextInt(); it does not consume the carriage return that has been pushed, so this is does at the next scan.nextLine();
You want your code to be
....
System.out.println("Something?: ");
int number = scan.nextInt();
scan.nextLine(); // add this
System.out.println("Something?: ");
String insurer = scan.nextLine();
The method nextInt() will not consume the new line character \n. This means the new line character which was
already there in the buffer before the nextInt() will be ignored.
Next when you call nextLine() after the nextInt(), the nextLine() will consume the old new line
character left behind and consider the end, skipping the rest.
Solution
int number = scan.nextInt();
// Adding nextLine just to discard the old \n character
scan.nextLine();
System.out.println("Something?: ");
String insurer = scan.nextLine();
OR
//Parse the string to interger explicitly
String name = scan.nextLine();
System.out.println("Something?: ");
String IntString = scanner.nextLine();
int number = Integer.valueOf(IntString);
System.out.println("Something?: ");
String insurer = scanner.nextLine();
All answers given before are more or less correct.
Here is a compact version:
What you want to do: First use nextInt(), then use nextLine()
What is happening: While nextInt() is waiting for your input, you press ENTER key after you type your integer. The problem is nextInt() recognizes and reads only numbers so the \n for the ENTER key is left behind on the console.
When the nextLine() comes again, you expect it to wait till it finds \n. But what do you didn't see is that \n is already lying on the console because of erratic behavior of nextInt() [This problem still exists as a part of jdk8u77].
So, the nextLine reads a blank input and moves ahead.
Solution: Always add a scannerObj.nextLine() after each use of scannerObj.nextInt()
I have created a Scanner with system.in.
How do I allow an input to be able to have commas in it without going to the next input?
For example:
System.out.print("Enter City, State.");
String location = scan.nextLine();
I cannot enter city,state because the language thinks I want to proceed to the next scanning input question. How do I allow commas in a scanning string?
*Whole Code
Scanner scan1 = new Scanner (System.in);
System.out.print ("City, State: ");
String location1 = scan.nextLine();
System.out.print ("Enter number: ");
number1 = scan.nextDouble();
System.out.print ("Enter number: ");
number2 = scan.nextDouble();
System.out.print ("City, State: ");
String name2 = scan1.nextLine();
System.out.print ("Enter #: ");
number3 = scan.nextDouble();
System.out.print ("Enter #: ");
number4 = scan.nextDouble();
scan.nextLine(); will return the entire line, commas or not.
If that isn't what's happening, then the problem must be elsewhere and you should provide more code.
Re: full code: That still works. What is the error you're getting / unwanted behavior?
What I think is happening is that the nextLine() is catching the end-of-line character from your previous input.
What happens:
Suppose you enter a number like 12.5 and press enter.
The buffer that Scanner reads from now contains 12.5\n where \n is the newline character.
Scanner.nextDouble only reads in 12.5 and \n is left in the buffer.
Scanner.nextLine reads the rest of the line, which is just \n and returns an empty string. That's why it skips to the next input: it already read "a line".
What I'd do to fix it:
System.out.print ("City, State: ");
String name2;
do{
name2 = scan1.nextLine();
}while( name2.trim().isEmpty() );
What this loop does is it keeps reading the next line until there is a line with something other than whitespace in it.
One possible solution: get the next line as you're doing and then use String#split on it to split on the comma (either that or use a second Scanner object that takes that String as input). If there is only one comma, then splitting on "," will give you an array that holds two Strings. You'll need to trim the second String to get rid of whitespace, either that or split on a more fancy regular expression.
You can either use split as mentioned above, or you could create another scanner on the next line, this would especially be useful if you have more than one fields separated by a ",".
System.out.print ("City, State: ");
Scanner temp = new Scanner(scan.nextLine());
temp.useDelimiter(",");
while(temp.hasNext()){
//use temp.next();
//Do whatever you want with the comma separated values here
}
But I still suggest that if you are just looking at something as simple as "City,State" , go for split.