What am I doing wrong do get this extra output? [duplicate] - java

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…

Related

input mismatch exception while using space in between words

I'm working on a project and I already finished it, I have really simple problem which makes me really confused. I'm trying to ask a user to enter a number from a menu and depending on that different things happen, but I get input mismatch exception whenever I type space in between words. I get that error on the last line of the code, please check my code below, Thanks.
System.out.println("Enter: " + "\n1.Enter Name" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
if(userChoice == 1) {
System.out.println("Enter name");
String name = kb.next();
}
if(userChoice == 2) {
System.out.println("Enter anohter name");
String anotherName = kb.next();
}
if(userChoice == 3)
break;
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
The issue is with your usage of Scanner#next(), in combination with wanting to input multiple "words" sepearted by a whitespace for example. (Disclaimer: I understand your question in the way that you want to enter multiple words for the "name" input, this answer takes that as a prerequisite)
See following excerpt from the Scanner#next() Javadoc:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
The default delimiter for the Scanner is a whitespace. So when you request a name from the user, and the user wants to enter "John Doe", only "John" will be read, and "Doe" will be left, most likely causing the error you are seeing.
The workaround I would propose is to use nextLine() to read the whole line while providing each input line by line.
However, be aware of this issue: Scanner is skipping nextLine() after using next() or nextFoo()?
Keeping that in mind, I would modify your code as follows:
String name = "";
String anotherName = "";
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
int userChoice = kb.nextInt();
while(userChoice != 3) {
kb.nextLine(); // consumes the newline character from the input
if(userChoice == 1) {
System.out.println("Enter name");
name = kb.nextLine(); // reads the complete line
// do something with name
} else if (userChoice == 2) {
System.out.println("Enter another name");
anotherName = kb.nextLine(); // reads the complete line
// do something with anotherName
}
System.out.println("Enter: " + "\n1.Enter Nmame" +"\n2.Enter another name" + "\n3.Exit");
userChoice = kb.nextInt();
}
Sidenotes:
I moved the declaration of your name and anotherName variables, as they don't have to be re-declared everytime.
However you should actually do something with them (e.g. save them in a list, or create some object with them) otherwise they will be lost on the next loop iteration.
You can omit the check for if (userChoice == 3) since this would never happen in combination with the while (userChoice != 3).
Example input:
Enter:
1.Enter Nmame
2.Enter another name
3.Exit
1
Enter name
John Doe
1.Enter Nmame
2.Enter another name
3.Exit
3

nextInt() following System.out.print()

System.out.print("Please enter the first number >");
System.out.print("Please enter the second number >");
The above code snippet results in this output:
"Please enter the first number >Please enter the second number >"
While this code snippet:
Scanner kb = new Scanner(System.in);
System.out.print("Please enter the first number >");
int num1 = kb.nextInt();
System.out.print("Please enter the second number >");
int num2 = kb.nextInt();
Results in this:
"Please enter the first number > 4"
"Please enter the second number > 5"
Why?
Normally using several System.out.print()'s in a row will result in text being printed out on the same line. But when using nextInt(); which skips over the carriage return control character, before the next System.out.print() the text is no longer printed on the same line.
Scanner.nextInt don't skip over the carriage return control character but ignores it. Therefore, this carriage return came from you hitting the key "Enter" to confirm your integer input.
You didn't give object kb though, so it was my guess was that you were reading stdin.

Why when the first time process go into the loop, it doesn't stop and wait for user input string first? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
Why when the first time process go into the loop, it doesn't stop and wait for user input string first, instead will print out the space and enter? It will only stop on the second time of loop and wait for the user to input something.
It's hacker rank 30 Days of code > Day 6 problem by the way.
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner stdin = new Scanner(System.in);
int input;
input = stdin.nextInt();
while( input-- >= 0 ){
String sentence = stdin.nextLine();
char[] CharArray = sentence.toCharArray();
for( int i=0; i < sentence.length() ; i=i+2 ){
System.out.print(CharArray[i]);
}
System.out.print(" ");
for( int i=1; i < sentence.length() ; i=i+2 ){
System.out.print(CharArray[i]);
}
System.out.println();
}
stdin.close();
}
When you enter a number, you also press the ENTER key to enter your input. So the following line consumes the number, but it does not consume the carriage return:
input = stdin.nextInt();
Instead, that carriage return is consumed in the first iteration of the loop by this line:
String sentence = stdin.nextLine();
In other words, it appears from your point of view that the first iteration of the loop did not prompt you for any input, because you unknowingly already entered it. If you want to avoid this, you can add an explicit call to Scanner.nextLine():
input = stdin.nextInt();
stdin.nextLine();
When you enter a number and press enter, nextInt() reads the integer you entered but the '\n' character is still in the buffer, so you need to empty it before entering the loop, so you can simply write : stdin.nextLine() before entering the loop
On first time, you are scanning twice.
input = stdin.nextInt();
it will wait for your input.once you give value it will move ahead. then again
String sentence = stdin.nextLine();
it will take enter(or carriage return) and print that with space.
after this it will work properly
Solution :
use stdin.nextLine(); just after input = stdin.nextInt();
You need to add one more -
stdin.nextLine();
after
input = stdin.nextInt();
without collecting it in some variable. This will consume the newline character appeared just after you finished inputting your integer in below line -
input = stdin.nextInt();

Scanner input skipping next input

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();"

Issues with nextLine(); [duplicate]

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();

Categories

Resources