Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code:

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

    }

}

When I run it and provide it with the input firstname lastname, I get the below exception:

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)

You can see below, when I only enter the firstname it works fine: 

Enter employee ID:

105

Enter employee name:

name

Enter supervisor ID:

501

I want to enter both the first name and last name. Can anyone tell me what I’m doing wrong here?

1 Answer

0 votes
by (19.7k points)

When you call nextInt() and hit enter, it doesn't move to the new line. Instead you can use scanner.nextLine() like below: 

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



 

Interested in Java? Check out this Java tutorial by Intellipaat. 

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 19, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Feb 18, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Mar 23, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer
asked Mar 20, 2021 in Java by Jake (7k points)

Browse Categories

...