Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 435
09Q71AO534 Avatar asked Jul 17 '13 04:07

09Q71AO534


People also ask

How do you read a string with a Scanner?

To read strings, we use nextLine(). To read a single character, we use next(). charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string.

How do you find the string in a Scanner class?

Using Scanner class nextLine() method: The Scanner class contains the nextLine() method which allows user input in the form of string. The method returns the entered string from the input buffer. If the method is unable to find any string input, it throws the NoSuchElementException.


2 Answers

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.

like image 79
Sajal Dutta Avatar answered Sep 27 '22 21:09

Sajal Dutta


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.

like image 29
blganesh101 Avatar answered Sep 27 '22 19:09

blganesh101