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.
Related
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.
Why nextLine() method doesn't work? I mean, I can not enter any sentence after the second scan call because the program runs to the end and exits.
Input: era era food food correct correct sss sss exit
Should I use another Scanner object?
import java.util.*;
public class Today{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str="";
String exit="exit";
System.out.println("Please enter some words : ");
while(true){
str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);
}
System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine();
System.out.println("the word you entered is : " + sentence1);
}
}
What Scanner#nextLine does is to
Advance 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.
Since your input is era era food food correct correct sss sss exit you read inside the while every word with Scanner#next, so when Scanner#nextLine is called it returns "" (empty string) because there is nothing left of that line. That's why you see the word you entered is : (at the begging of the text is the empty string).
If you would have used this input: era era food food correct correct sss sss exit lastWord you would have seen the word you entered is : lastWord
The only thing you need to do in order to fix this is to call scan.nextLine(); first to move to the next line for the new input the user is going to provide and then get the new word with Scanner#nextLine() like this:
Scanner scan = new Scanner(System.in);
String str="";
String exit="exit";
System.out.println("Please enter some words : ");
while(true){
str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);
}
scan.nextLine(); // consume rest of the string after exit word
System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine(); // get sentence
System.out.println("the word you entered is : " + sentence1);
Demo: https://ideone.com/GbwBds
I am trying to apply 2 conditions: read a character at a time and require alpha character input for the same scanner input:
Any suggestions on how to apply these conditions and continue checking each character user inputs?
Scanner lastname = new Scanner(System.in);
System.out.println("Please enter the first letter of last name:");
lastname.useDelimiter("(?<=.)");
if (lastname.hasNext())
System.out.println("character: [" + lastname.next() + "]");
if (!lastname.hasNext("[A-Za-z]+")); {
System.out.println("You are not a robot so do not use numeric characters.");
System.out.println("Please enter letter:");
lastname.next();
Don't change the delimiter; change your logic.
Always just read one character, but test it using code like this:
String s = scanner.next();
if (Character.isDigit(s.charAt(0)))
or using regex:
if (s.matches("[a-zA-Z]+"))
Say I had the Scanner method, and I want to print the user input after that.
Take this code for instance:
String randomWords;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter two words separated: ");
randomWords = kb.next();
System.out.println(randomWords);
And if the two separated words entered were
hello world
Only
hello
is printed
Why is this? and how can I print both of the words with the space included?
Thank you.
Use Scanner#nextLine() instead,
This method returns the rest of the current line, excluding any line
separator at the end.
randomWords = kb.nextLine();
Scanner#next() reads the next complete token basing on the delimiter.
Finds and returns the next complete token from this scanner. A
complete token is preceded and followed by input that matches the
delimiter pattern
As default delimiter of the scanner is whitespace, you should explicitly define the delimiter for your scanner using Scanner#useDelimiter(str).
If you use \n next line as delimiter your curretn code would work.
Scanner kb = new Scanner(System.in).useDelimiter("\n");
System.out.print("Please enter two words separated: ");
randomWords = kb.next();
System.out.println(randomWords);
Use Scanner.nextLine() method to read up to the line break (noninclusive).
randomWords = kb.nextLine();
public static void main(String[] args) {
String randomWords;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter two words separated: ");
randomWords = kb.nextLine();
System.out.println(randomWords);
}
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.