some questions about java Scanner - java

enter image description here
}
Why does the code on line 6 have the same effect on line 8? Is there no distinction between the starting point of this while loop?

Also, you should follow this tips to use the Scanner properly:
Mixing any nextXXX method with nextLine from the Scanner class for user input, will not ask you for input again but instead result in an empty line read by nextLine.
To prevent this, when reading user input, always only use nextLine. If you need an int, do
int value = Integer.parseInt(scanner.nextLine());
instead of using nextInt.
Assume the following:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
int age = sc.nextInt();
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
When executing this code, you will be asked to enter an age, suppose you enter 20.
However, the code will not ask you to actually input a name and the output will be:
Hello , you are 20 years old.
The reason why is that when you hit the enter button, your actual input is
20\n
and not just 20. A call to nextInt will now consume the 20 and leave the newline symbol \n in the internal input buffer of System.in. The call to nextLine will now not lead to a new input, since there is still unread input left in System.in. So it will read the \n, leading to an empty input.
So every user input is not only a number, but a full line. As such, it makes much more sense to also use nextLine(), even if reading just an age. The corrected code which works as intended is:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
// Now nextLine, not nextInt anymore
int age = Integer.parseInt(sc.nextLine());
System.out.println("Enter your name:");
String name = sc.nextLine();
System.out.println("Hello " + name + ", you are " + age + " years old");
The nextXXX methods, such as nextInt can be useful when reading multi-input from a single line. For example when you enter 20 John in a single line.

Related

i want to know how Scanner code works in Java

it's my first time to ask in this community
first, please excuse my poor english in advance
i want to know how Scanner code works
Scanner scanner = new Scanner(System.in); ------Call it "A" for convenience
System.out.print("first number:");
String strNum1 = scanner.nextLine();
System.out.print("second number:"); -----Call it "B" for convenience
String strNum2=scanner.nextLine();
int num1 = integer.parseInt(strNum1); ---- Call it "C" for convenience
int num2 = integer.parseInt(strNum2);
int result = num1 + num2;
System.out.println("Add result: " + result);
Question is about Process of
in the moment i input some number in Console after [code above] is implemented
how [code above] interact(?) with result in Console
For example , when i input code above, run it
and i input some number in console
(1) input 1 -> output in console - "first number:1"
(2) input 3 -> output in console - "first number:1" "Second number:3" "Result: 4"
i can see this
So,
does it mean, when the process up to (1) is input, Progress to "A" shows up?
if it's right, that 'scanner.nextLine()' is input at first as "1" Is the process of (1)
But, although the variable 'strNum1' is not run by 'System.out.println()'
Why can i see this number "1" ??
And,
Why doesn't System.out.print("first number") appears at first,
unless i input some number like "1"
in connection with String strNum1 = scanner.nextLine();
You dont need to get a string from the user and after that parse it to int If you only want to connect two numbers , you can get a int from the user and use with scanner.nextInt() , This will save you code lines and efficiency.
Scanner scanner = new Scanner(System.in);
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = "+ result);
When you working with string you need to use with scanner.nextLine(); or if you work with a number that start with 0(like maybe id) string is the right thing , because int cant be start with 0.
Okay, let's dig in it (yes, line by line).
You create the Scanner object which takes as input the common input stream provided by the System.in, in that case the console itself.
Then, you are calling System.out.print which is different from System.out.println
System.out.print will simply append to the current state of the console the value you provided
Scanner gets call in using the nextLine() methods, this block the process until some input is inserted inside the console terminal, this is how usually the console works, you input something, press enter and it gets executed. More or less, it's the same in that case, scanner wait until you provide a line separator (press enter).
The exact same stuff happens for the scanner B
The numbers gets parsed and in the end their output is appended to the terminal with System.out.println()
Let's summarise:
Scanner block the thread until it receives an input, then it gets parsed and the normal flow of the routine goes on. A Scanner breaks its input into tokens using a delimiter pattern, in that case of nextLine() the delimiter pattern is the System.lineSeparator();

Java - Scanner execute only the Int and "skip" the Strings data types when i input String data before the Int ones [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 7 years ago.
While I'm working with java.util.Scanner, I tried to use integers and Strings at data input.
The problem that I faced is, when I input an Int data before a String one, the console skip the String data and go immediately to the next Int one.
Here is my simple problem where the problem is happening :
package justForTest;
import java.util.Scanner;
public class EmptySpaceWorkshop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("- Enter your Name : ");
String name = input.nextLine();
System.out.print("- Enter your IC number : ");
int icNumber = input.nextInt();
System.out.print("- Enter your Place of birth : ");
String placeOfBirth = input.nextLine();
System.out.print("- Enter your Age : ");
int age = input.nextInt();
System.out.println("There once was a wonderful person named " + name+ ", His IC number is " + icNumber );
System.out.println(". He/She is " + age + " years old. She/He was born at " + placeOfBirth );
}
}
And here is my output:
- Enter your Name : Ali HISOKA
- Enter your IC number : 123456
- Enter your Place of birth : - Enter your Age :
I tried a lot to fix this problem. The only solution I could came up with is using input.next(); instead of input.nextLine(); . However, this solution is USELESS for me because as you guys know, when using input.next(); we can only type One Single Word, unlike input.nextLine(); we can type a lot of words which is the thing that I'm looking for. Also I DO NOT want to re-sort (re-arrange) my input and type the Strings data first, then following by the Int data to solve my problem. I want my data to be at the same sort as you seen above in my simple program ( Enter Name, Enter IC Number, Enter Place of Birth, then Enter age). So can I solve this problem ?
I searched a lot on the internet for someone got a problem as mine, but I couldn't find a question and solution for a problem looks exactly like mine.
I already know the reason and the explanation of my problem which is explained by
Joshua
"The reason for the error is that the nextInt only pulls the integer,
not the newline. If you add a in.nextLine() before your for loop, it
will eat the empty new line and allow you to enter 3 names."
but still it's not helpful for solving my problem.
Think of your input as a single string:
"Ali HISOKA\n123456\nPLACE\n99"
next() consumes the first word, up to first white space - e.g. " " or "\n"
nextLine() consumes the first word, up to first new line character
nextInt() consumes first word, as next(), and parses it to int - it will throw an exception if the word cannot be parsed.
Now, let's have a look what your calls are consuming:
nextLine() will return "Ali HISOKA", the remaining string is "123456\nPLACE\n99"
nextInt() will return int 123456, the remaining string is "\nPLACE\n99"
nextLine() will return empty string "", the remaining string is "PLACE\n99"
nextInt() will throw an exception, because it will try to parse "PLACE" to int.
The trick is in step 2 - although nextInt() consumes all white spaces between words, it however does not consume new line character, hence nextLine() in step 3 reads empty string because "\n" is first character in the remaining string.
There are two solutions:
Instead of using nextInt() you can read and parse the whole line Integer.parseInt(input.nextLine()). If the line contains a few words, e.g. "1234 abc" it will throw the exception.
Call input.nextLine() after calling nextInt(), so it consumes the remaining string up to first new line character. For input "1234 abc" it will ignore everything after the number.
I would recommend the first solution, because when you are asked for the number and you answer "123 abc", it is not a valid answer. In such case the user should be told that the input is invalid, instead of taking only a valid part from that answer - user would have no clue that part of his answer was ignored.
From what I can see it appears that the readLine() is just consuming the newline left after the int was taken from the buffer. A better way to fix this is to use nextLine() to get a string value and convert it:
int icNumber = Integer.parseInt(input.nextLine());
This is a bit confusing because the code you posted does not show your original problem, but the situation after putting in a workaround.
You need to skip the newline after nextInt()
System.out.print("- Enter your IC number : ");
int icNumber = input.nextInt();
input.skip("\\n");
Without the skip, input.newLine (for the place of birth) will match the newline after the entered IC number and you will be prompted for the age.
I tried your code at my machine without making any changes and Its working fine.Below is my output.
Enter your Name : yash
Enter your IC number : 12
Enter your Place of birth : alg
Enter your Age : 25
There once was a wonderful person named yash, His IC number is 12
. He/She is 25 years old. She/He was born at alg

Skip over inputing string [duplicate]

This question already has answers here:
Scanner issue when using nextLine after nextXXX [duplicate]
user input string and integers in Java [duplicate]
(3 answers)
Closed 8 years ago.
int id;
float grade;
String name;
Scanner z= new Scanner(System.in);
System.out.println("Give the id:\n");
id=z.nextInt();
System.out.println("your id is :"+id+"\n");
System.out.println("Give the name:");
name=z.nextLine();
System.out.println("your name is :"+name);
System.out.println("Give the grade:\n");
grade=z.nextFloat();
The problem goes like this.It inputs the integer but when it comes to the String, it prints "Give the name" but it doesn't waits until I type something, it skips to the next instruction.
Why's that?
You have used name=z.nextLine(), hence such behavior, Replace it with name=z.next(). Below is the edited code:
int id;
float grade;
String name;
Scanner z= new Scanner(System.in);
System.out.println("Give the id:\n");
id=z.nextInt();
System.out.println("your id is :"+id+"\n");
System.out.println("Give the name:");
name=z.next();
System.out.println("your name is :"+name);
System.out.println("Give the grade:\n");
grade=z.nextFloat();
When you read int value using nextInt, it reads only the int value, it skips the new line character. The latter will be read in the next nextLine causing it to skip the "real" input.
You can fix this by adding another nextLine before the "real" nextLine, it'll swallow the '\n' that you don't want to read.
Important note: Don't use int to store ID value! Use String instead!
The problem is with the input.nextInt() command it 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()
id = z.nextInt();
System.out.println ("your id is :"+id+"\n");
z.nextLine ();// add this line between the next line read
System.out.println("Give the name:");
or
id = Integer.parseInt(z.nextLine());
System.out.println ("your id is :"+id+"\n");
System.out.println("Give the name:");

InputMismatchException with Scanner

I have the following Java code:
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter your name>>");
String name = input.next();
System.out.println("Enter your year of birth>>");
int age = input.nextInt();
System.out.println("Name: " + name);
System.out.println("Year of Birth: " + age);
System.out.println("Age: " + (2012 - age));
} catch (InputMismatchException err) {
System.out.println("Not a number");
}
When I enter a name with a space (e.g. "James Peterson"), I get the next line output correctly (Enter your year of birth) and then an InputMismatchException immediately. The code works with a single name without spaces. Is there something I'm missing?
System.out.println("Enter your name>>");
String name = input.next();
System.out.println("Enter your year of birth>>");
int age = input.nextInt();
Scanner, breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
When you enter "James Peterson", Scanner#next() takes "James" as a token and assigns it to String name and then you do a Scanner#nextInt() which takes "Peterson" as the next token, but it is not something which can be cast to int and hence the InputMismatchException asnextInt() will throw an InputMismatchException if the next token does not match the Integer regular expression, or is out of range.
Actually the problem in your code has been clearly pointed out. In your case, there are two typical ways to achieve that:
One
Using useDelimiter method to delimite the input and after each input, you need to hit the Enter.
Sets this scanner's delimiting pattern to a pattern constructed from the specified String.
In your case, you need to
Scanner sc = new Scanner(System.in);
sc.setDelimiter("\\n");
// hit the "Enter" after each input for the field;
Two
Also you can achieve the same result using readLine
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
In this way, you can do
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name>>");
String name = sc.nextLine();
...
System.out.println("Enter your year of birth>>");
int age = sc.nextInt();
P.S.
Actually you can achieve it in a more restrictive way, controlling the pattern using next(Pattern pattern), if you need it.
int age = sc.next(Pattern.compile("\\d+{1,3}"));
In this case, if the input DOES NOT match the pattern, it will throw InputMismatchException as you were trying to nextInt while the input is a string.
When I enter a name with a space (e.g. "James Peterson"), I get the next line output correctly (Enter your year of birth>>) and then an InputMismatchException immediately.

System.out.println repeating itself

Would anyone point me in the right direction, of why when i use a for loop the println function comes up two times in the output. Thanks
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of employees to calculate:");
int numberEmployees = scan.nextInt();
for(int i=0; i<numberEmployees; i++){
System.out.println("Enter First Name:");
name = scan.nextLine();
System.out.println("Enter Last Name:");
last = scan.nextLine();
System.out.println("Enter Document #:");
document = scan.nextInt();
System.out.println("Enter Basic Salary");
basicSalary = scan.nextInt();
System.out.println("Enter # of Hours");
hours = scan.nextInt();
}
}
OUTPUT
Enter the number of employees to calculate:
1
Enter First Name:
Enter Last Name:
daniel
Enter Document #:
The problem is that when you entered 1 with a new line, the nextInt() function doesn't remove the newline that you had from entering in the 1. Change your calls to scan.nextInt() to Integer.parseInt(scan.nextLine()) and it should behave the way you want.
To further explain; here's stuff from the Java API.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
and
The next() and hasNext() methods and their primitive-type companion
methods (such as nextInt() and hasNextInt()) first skip any input that
matches the delimiter pattern, and then attempt to return the next
token. Both hasNext and next methods may block waiting for further
input.
So, what evidently happens (I didn't see anything on the page to confirm it) is that after next(), hasNext(), and their related methods read in a token, they immediately return it without gobbling up delimiters (in our case, whitespace) after it. Thus, after it read in your 1, the newline was still there, and so the following call to nextLine() had a newline to gobble and did so.
It appears that the newline character remains in your input after the first entry. When the next input is requested, the Scanner sees a newline character and interprets it as the end of the input. This makes it appear to skip every other input request. I would suggest checking out the Java API docs as to the exact behavior of Scanner's methods.

Categories