I am a newbie with java and the class scanners.
I have two Codes and I dont get the point why one of them throws a InputMismatchException.
I look forward to the answers.
Here both codes:
1st one with the Exception Error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName, completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name and your age: ");
completeName = sc.next();
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your complete name and your age:
Peter Henrik 22
(InputMismatchException)
2nd one with no error:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + firstName + " " + lastName);
System.out.println("Your age is: " + age);
}
Console:
Please enter your first name:
Peter
Please enter your last name:
Henrik
Please enter your age:
22
Your complete name is: Peter Henrik
Your age is: 22
Your first code throws InputMismatchException because sc.next() reads the first complete token ("Peter") up to the whitespace (since whitespace is the default delimiter for Scanner in Java), thus after that, the sc.nextInt() method will read "Henrik" which is a String unlike your expectation to read the age (22).
Here's what you can do instead in order to read the complete name of the user as well as the age [CONDITION: You'll have to enter age in a new line]:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String firstName, lastName,completeName;
int age;
System.out.println("Please enter your first name: ");
firstName = sc.nextLine();
System.out.println("Please enter your last name: ");
lastName = sc.nextLine();
System.out.println("Please enter your complete name: ");
completeName = sc.nextLine();
System.out.println("Please enter your age: ");
age = sc.nextInt();
System.out.println("Your complete name is: " + completeName);
System.out.println("Your age is: " + age);
}
PS: An alternate solution can be to read the complete name and the age in a single line as you did and then split up the tokens using the String split() method in Java.
Having a look at the Javadoc of Scanner#next() will tell you the following:
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.
Knowing this, you provide the following input
Peter Henrik 22
and try to read this input via the following
completeName = sc.next();
age = sc.nextInt();
The call to sc.next() will read the first complete token up to the whitespace, which is "Peter".
So Henrik 22 is still available in the Scanner buffer.
Therefore sc.nextInt() will read Henrik and try to parse it to an int hence the InputMismatchException.
To read both tokens to get the complete name, simply change
completeName = sc.next();
to
completeName = sc.next() + " " + sc.next();
However, names don't always consist of only two parts. Since there could be names that more than two single tokens, you should / could do it like the following (provided you still want to enter the complete name and age in one line):
String line = sc.nextLine(); // read the whole line
// everything up to the last token is the name
completeName = line.substring(0, line.lastIndexOf(" "));
// last token is the age
age = line.substring(line.lastIndexOf(" ") + 1);
Related
The Following code is a simple java program where I am just getting an input of a student details but the program doesn't do anything it just stays like this no compilation error or does not take any input
import java.util.Scanner;
public class Scannerexample {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int Rollno = scan.nextInt();
String firstname = scan.nextLine();
String lastname = scan.nextLine();
String Department = scan.nextLine();
Boolean Result = scan.hasNext();
char gender = scan.next().charAt(0);
System.out.println("Enter Rollno "+ Rollno);
System.out.println("Enter Firstname "+ firstname);
System.out.println("Enter Lastname "+ lastname);
System.out.println("Enter Department "+ Department);
System.out.println("Enter Result "+ Result);
System.out.println("Enter Gender "+ gender);
scan.close();
}
}
Each call of scan.nextSomething waits for input. So the way you have written the program you wait for inputting of all the fields and then print them. Try typing some fields and press enter to see the result in the end.
What you probably wanted is something like:
System.out.println("Enter rollno: ");
int rollno = scan.nextInt();
System.out.println("You entered rollno: "+ rollno);
Also there are some java conventions which are nice and make the code readable :) For example variables start with lowercase and classes are in CamelCase
So what your Code does is every time you call
scan.nextLine();
The Program waits for your Input, until you hit 'Enter'.
So if you want to write something before the Input, you have to do it like this:
System.out.print("Enter Rollno: ");
int rollno = scan.nextInt();
System.out.print("Enter Firstname: ");
String firstname = scan.next();
// Any more.
Keep an eye that you only use 'print()' instead of 'println()' so that your input is on the same Line.
Also use scan.next(), to only grab the input, and not the complete line in terminal.
be carefull with scan.next() or scan.nextLine()
System.out.print("Enter Rollno: ");
int rollno = scan.nextInt();
System.out.print("Enter Firstname: ");
String firstname = scan.next();
System.out.println(firstname);
// Any more.
System.out.print("Enter Lastname: ");
String lastname = scan.next();
System.out.println(lastname);
in this case, if you input Firstname as: John Doe, it will not let you to input Lastname, because it will read next string in line.
scan.next() read strings up to "space", then another scan.next() will read next strings up to next "space".
I need get a number from prompt, and juste after I need get a String list from prompt. I have a problem. Is it OK if the 1st question ask a string with nextLine() see this post.
Java code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console result:
Enter a number:
2
Enter a name list:
Enter last name:
1st response is 2 + enter
but juste after 2 + enter, the program display Enter a name list:
Enter last name:
I would use input.next() instead of input.nextLine() as next blocks for user input while nextLine moves the scanner past the current line and it buffers all the inputs until it finds a line separator.
or use nextLine() after nextInt to consume the linefeed which is left by nextInt
Solution add input.nextLine(); juste after int num = input.nextInt();.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number:");
int num = input.nextInt();
input.nextLine();
System.out.println("Enter a name list:");
String nameList = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
input.close();
System.out.println(num + " * " + nameList + " ** " + lastName);
}
console:
Enter a number:
2
Enter a name list:
aa bb cc
Enter last name:
dd
2 * aa bb cc ** dd
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(25 answers)
Closed 5 years ago.
So everything compiles fine but when I run it the line asking for city and the line asking for zip both print out at the same time. I need them to print individually so the user can answer.
import java.util.Scanner;
public class PersonalInfo
{
public static void main(String[] args)
{
String name, city, state, major;
int zip, phone, address;
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your name: ");
name = scanner.nextLine();
System.out.println("please enter your address number: ");
address = scanner.nextInt();
System.out.println("Please enter the name of the city you live in: ");
city = scanner.nextLine();
System.out.println("Please enter your zip code: ");
zip = scanner.nextInt();
System.out.println("Please enter the name of the state you live in: ");
state = scanner.nextLine();
System.out.println("Please enter your phone number(format ##########): ");
phone = scanner.nextInt();
System.out.println("Please enter your college major: ");
major = scanner.nextLine();
System.out.println(name + "\n" + address + "," + city + "," + state +
"," + zip + "\n" + phone + "\n" + major);
}
}
The only method that consume newline of the input is nextLine(), so if you use nextInt() and then you want to capture anything else you have to call a nextLine() after you call nextInt().
For example:
System.out.println("please enter your address number: ");
address = scanner.nextInt();
scanner.nextLine();
System.out.println("Please enter the name of the city you live in: ");
city = scanner.nextLine();
Output:
please enter your address number:
567
Please enter the name of the city you live in:
Puerto Montt
I'm new to java and I made this program, the problem I'm asking the user to input their age and name then the program should use the input to print the statement. however the when I type the age then press enter the program executes all the statements without waiting for me to enter my name.. how can I fix this?
Scanner input = new Scanner(System.in);
int age;
String name;
System.out.println("Please enter your age ");
age = input.nextInt();
System.out.println("and now enter your name");
name = input.nextLine();
System.out.println("Your name is " +name + " and you're " +age + "years old");
You can use nextLine() for both:
System.out.println("Please enter your age ");
age = Integer.parseInt(input.nextLine());
System.out.println("and now enter your name");
name = input.nextLine();
The problem is that when you hit Enter after you input the age, the resulting newline is interpreted as the end of the input for the following nextLine().
You could also use next() instead of nextLine(), but then John Doe would be interpreted as just John because next() uses whitespace as a separator.
Use next() instead of nextLine() at name variable.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int age;
String name;
System.out.println("Please enter your age ");
age = input.nextInt();
System.out.println("and now enter your name");
name = input.next();
System.out.println("Your name is " +name + " and you're " +age + " years old");
}
Here is my code
Scanner keyboard = new Scanner(System.in);
System.out.print("Last name: ");
lastName = keyboard.nextLine();
System.out.print("First name: ");
firstName = keyboard.nextLine();
System.out.print("Email address: ");
emailAddress = keyboard.nextLine();
System.out.print("Username: ");
username = keyboard.nextLine();
and it outputs this
Last name: First name:
Basically it skips letting me enter lastName and goes straight to the prompt for firstName.
However, if I use keyboard.next() instead of keyboard.nextLine(), it works fine. Any ideas why?
Let me guess -- you've got code not shown that uses the Scanner above the attempt to get lastName. In that attempt, you're not handling the end of line token, and so it's left dangling, only to be swallowed by the call to nextLine() where you attempt to get lastName.
For example, if you have this:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt(); // dangling EOL token here
System.out.print("Last name: ");
lastName = keyboard.nextLine();
You're going to have problems.
One solution, whenever you leave the EOL token dangling, swallow it by calling keyboard.nextLine().
e.g.,
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
keyboard.nextLine(); // **** add this to swallow EOL token
System.out.print("Last name: ");
lastName = keyboard.nextLine();