How to read strings from a Scanner in a Java console application? - java

import java.util.Scanner;
class MyClass
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
System.out.println("Enter employee name:");
name = scanner.next();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();
}
}
I got this exception while trying to enter a first name and last name.
Enter employee ID:
101
Enter employee name:
firstname lastname
Enter supervisor ID:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at com.controller.Menu.<init>(Menu.java:61)
at com.tests.Employeetest.main(Employeetest.java:17)
but its working on if I only enter the first name.
Enter employee ID:
105
Enter employee name:
name
Enter supervisor ID:
501
What I want is to read the full string whether it is given as name or as firstname lastname. What's the problem here?

Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();
Calling nextInt() was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine() after that does the work.

What you can do is use delimeter as new line. Till you press enter key you will be able to read it as string.
Scanner sc = new Scanner(System.in);
sc.useDelimiter(System.getProperty("line.separator"));
Hope this helps.

Replace:
System.out.println("Enter EmployeeName:");
ename=(scanner.next());
with:
System.out.println("Enter EmployeeName:");
ename=(scanner.nextLine());
This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

You are entering a null value to nextInt, it will fail if you give a null value...
i have added a null check to the piece of code
Try this code:
import java.util.Scanner;
class MyClass
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int eid,sid;
String ename;
System.out.println("Enter Employeeid:");
eid=(scanner.nextInt());
System.out.println("Enter EmployeeName:");
ename=(scanner.next());
System.out.println("Enter SupervisiorId:");
if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
sid=scanner.nextInt();
}//null check
}
}

Related

Difference between two codes and InputMismatchException

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

What does the error " java.util.NoSuchElementException: No line found" mean in java?

I have a list called contacts which accepts objects of type contact.
The method i wrote to add a contact to the list always throws the error "java.util.NoSuchElementException: No line found", when the method is called more than once in a row.
Apparently the error stems from the line
name = scanner.nextLine();
I hope someone can point out the problem. Thanks in advance.
public void addNewContact() {
Scanner scanner = new Scanner(System.in);
String name;
int number;
System.out.print("Enter contact name: ");
name = scanner.nextLine();
System.out.print("Enter contact number: ");
number = scanner.nextInt();
scanner.nextLine();
Contact contact = new Contact(name, number);
contacts.add(contact);
scanner.close();
}
All you need to do to fix this, is to remove
scanner.close(). Instead of using scanner.close(), you should put the entire function in while(true){..} and use a break; to stop it. You also need to change all of the .nextLine() to .next(). Do not change the .nextInt() This is because .nextLine() is more buggy than .next(). After fixing these two parts, your code should work properly.
Final product:
public void addNewContact() {
while(true){
Scanner scanner = new Scanner(System.in);
String name;
int number;
System.out.print("Enter contact name: ");
//name = scanner.nextLine(); CHANGED
name = scanner.next();
System.out.print("Enter contact number: ");
number = scanner.nextInt();
Contact contact = new Contact(name, number);
contacts.add(contact);
//scanner.close(); REMOVED
break;
}
}

Java Scanner Input , there are no compilation errors neither successful input

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".

Scanner Object skips to second Scanner Object

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

Scanner nextLine() occasionally skips input

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

Categories