nextInt() following System.out.print() - java

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.

Related

Java: Try to Understand Getting Inputs from Users Using Scanner

I have this programs and a few questions regarding to how .next(), .nextInt(), .hasNext() and .hasNextInt() of Scanner class work. Thank you in advance for any of your help :)
import java.util.Scanner;
public class test {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
int age;
System.out.print("Please enter your age: ");
while (!console.hasNextInt()) {
System.out.print("Please re-enter your age: ");
console.next();
}
age = console.nextInt();
System.out.println("Your age is "+age);
}
}
1/ When !console.hasNextInt() is executed for the first time, why does it ask for an input?
I thought at first the console is empty, so !console.hasNextInt() is True (empty is not an int), then it should go directly from "Please enter your age: " to "Please re-enter your age: " but my thought seems to be wrong.
Here, the user needs to enter something before "Please re-enter your age: " is printed.
2/ The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
3/ For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
The java.util.Scanner.hasNextInt() method returns true if the next
token in this scanner's input can be interpreted as an int value in
the default radix using the nextInt() method.
When you start with a non integer input, hasNextInt() will be false and you will enter while loop. Then it will prompt you to re-enter your age. But if you start with integer, you won't enter the loop. Your age will be printed.
console.next() means it takes next input token and returns String. If you write down your code as:
String s = null;
while (!console.hasNextInt()) {
s = console.next();
System.out.println("You entered an invalid input: " + s);
System.out.print("Please re-enter your age: ");
}
console.next() is being used for handling the non-integer inputs. Now, if you enter a non-integer input twenty, you'll see that console.hasNextInt() will be false and console.next() will read it.
hasNextInt() waits for an input string and then tells you if can be converted to an int. With that in mind, let's go over your questions:
When !console.hasNextInt() is executed for the first time, why does it ask for an input?
Because it blocks until there's some input from the console.
The data type of console.next() is always a String (I tried making int s = console.next(); and it gave an error), then why isn't this a infinite loop?
Because hasNextInt() returns true when the input can be converted to an int, for example "21".
For an instance, when it comes to console.next();, I input 21. Why does age have the value of 21? I thought because of console.hasNextInt(), I need to enter another number, and that new number will be the value of age.
Calling next() doesn't wait for a new input, it just swallows the input that was tested by hasNextInt() so the scanner can move on to the next one. It could have been the first statement in the loop, with the same effect.

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

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…

Getting java.util.InputMismatch upon typing "exit"

Scanner input = new Scanner (System.in);
System.out.println("Enter -1 to exit the program");
System.out.println("Enter the search key: ");
int searchkey = input.nextInt();
String exit = input.nextLine();
while (!exit.equals("exit"))
{
linear(array, searchkey);
binary(array,searchkey);
System.out.println();
System.out.println("Enter exit to end the program");
System.out.println("Enter the search key: ");
searchkey = input.nextInt();
exit = input.nextLine();
}
I am getting an InputMismatch exception. I know this is because of searchkey. How can I use the string to exit the program?
If "exit" is the first thing you type when you run the program then you will crash. This is because the first read in of the input is input.nextInt(). If you type "exit" and input expects an int, it will throw the InputMismatch exception.
To correct for this, you can use input.next() if you dont know what you are going to get. Then you can do your own parsing on the input.
You are calling nextInt without checking it is an int. You need to check hasNextInt() first because they might have typed "exit" as you instructed.
My guess is you type "exit" immediately after the print statement, so it gets captured by
searchkey= input.nextInt();
If nextInt()gets a non-int passed to it, it will cause an exception.
input.nextInt() expects you to enter an integer (like -1, 0, 1, 2..) If you introduce "exit" then it will throw that exception.
Maybe if you change the position of your prompt and your instructions?
System.out.println("Enter -1 to exit the program");
int searchkey= input.nextInt(); // Only integers are allowed
System.out.println("Enter the search key: ");
String exit = input.nextLine(); //Introduce any string, like exit or apples.
System.out.println will not know what you are going to do, that is something that is meaningful for you, no for the program itself.
This is your current output:
Enter -1 to exit the program
Enter the search key:
<here you should type an integer and enter>
<here you should type a String>
It seems that you don't need the integer at all, but a proper output ought be:
Enter -1 to exit the program
<here you should type an integer and enter>
Enter the search key:
<here you should type a String>
After calling nextInt or nextLine, your console will stop printing until you enter something. If you enter "exit" when nextInt was called you will get that exception, just try to do the math "exit"+5.

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

Scanning a String with a comma

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.

Categories

Resources