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();
Related
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);
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".
So I am doing a project to put values into a scanner object and retrieve them. I am having a problem with the first input. The user is asked to input an ID and then should be asked for the last name.The problem is that when I run the first question it displays it but skips the first scanner input and jumps to the second question and input returns to normal. So what is happening here? And how do I solve this?
//Prompt user for each value
System.out.println("Enter employee Id number:");
String inputId = scanner.nextLine();
System.out.println("Enter employees last name:");
String inputLastName = scanner.nextLine();
System.out.println("Enter employees first name:");
String inputFirstName = scanner.nextLine();
System.out.println("Enter employees salary:");
String inputSalary = scanner.nextLine();
Double inSalary = Double.parseDouble(inputSalary);
i have same problem with you, and i change .nextLine() with .next()
and that is how i fix my problem
try this
System.out.println("Enter employee Id number:");
String inputId = scanner.next();
System.out.println("Enter employees last name:");
String inputLastName = scanner.next();
System.out.println("Enter employees first name:");
String inputFirstName = scanner.next();
System.out.println("Enter employees salary:");
String inputSalary = scanner.next();
Double inSalary = Double.parseDouble(inputSalary);
I've seen a couple of threads that are similar to this question, but had trouble finding the solution to my specific question.
The code I am writing is for a teacher to input a student's name and grades and receive an output of the final letter grade.
The area I am having trouble with is the last name input gets grouped together with the first name input, instead of asking the question by itself. How do I prompt these to appear as separate questions?
import java.util.*;
public class AssignmentTest {
public static void main (String [] args) {
Scanner console = new Scanner (System.in);
int iStudentID = 0; //StudentID
String sLastName = ""; //Last Name
String sFirstName = ""; //First Name
int iAssignmentsScore = 0; //Assignment Input
int iQuizzesScore = 0; //Quizzes Input
int iMidtermsScore = 0; //Midterm Input
int iFinalScore = 0;; //Final Input
//USER INPUT
//StudentID Input
System.out.println("Please enter the StudentID: ");
iStudentID = console.nextInt() ;
//Last Name Input
System.out.println ("Please enter the student's last name: ");
sLastName = console.nextLine() ;
//First Name Input
System.out.println ("Please enter the student's first name: ");
sFirstName = console.nextLine() ;
//Assignment Input
System.out.println ("Please enter the student's assignment score: ");
iAssignmentsScore = console.nextInt() ;
//Quiz Input
System.out.println ("Please enter the student's quiz score: ");
iQuizzesScore = console.nextInt ();
//Midterm Input
System.out.println ("Please enter the student's midterm score: ");
iMidtermsScore = console.nextInt ();
//Final Input
System.out.println ("Please enter the student's final score: ");
iFinalScore = console.nextInt ();
}
}
Since sFirstName and lFirstName , each consist of a word you should use
next()
Finds and returns the next complete token from this scanner.
Instead of
nextLine()
Advances this scanner past the current line and returns the input that
was skipped.
#madprogrammer has better explanation:
Actually, the issue is after iStudentID = console.nextInt() ; returns,
there is still a new line character in the buffer, so that when
sLastName = console.nextLine() ; is called, it skips of this
automatically (returning an empty String) - this is a very common
mistake
try this
System.out.println ("Please enter the student's last name: ");
sLastName = console.nextLine() ;
console.nextLine();
I think this may be as simple as adding another new line character \n. For example
System.out.println ("\nPlease enter the student's first name: ");
you should use next() instead of nextLine()
I'm attempting to scan in strings one after another and some may contain spaces. As my code functions currently it will only work if each string you type in is one word. What's the proper way to scan in consecutive lines of text, regardless of there being spaces in the line or not.
System.out.print("Enter your first name: ");
fName = scan.next();
System.out.print("Enter your last name: ");
lName = scan.next();
System.out.print("Enter your street and house number: ");
address = scan.next();
System.out.print("Enter your city: ");
city = scan.next();
System.out.print("Enter your state: ");
state = scan.next();
System.out.print("Enter your telephone number (no spaces): ");
teleNum = scan.next();
System.out.print("Enter your zip code: ");
zip = scan.next();
String[] prompts = {
"Enter your city: ",
"Enter your state: ",
};
Scanner scanner = new Scanner(System.in);
String line = "";
for (String prompt : prompts) {
System.out.println(prompt);
if (scanner.hasNextLine()) {
line += scanner.nextLine();
}
}
System.out.println(line);