Skip to content
Advertisement

Exception in thread main java.util.InputMismatchException error

I have a question on what’s going on, whenever I try to compile it it keeps giving me an error like this:

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 Person.main(Person.java:38)

All I want is for the user to be able to input their age and name and have it stored in the “age” and “name” variables, then have it print it out in the bottom string. And if someone would like to help me clean up my code as well, it wouldn’t hurt..

import java.util.*; 
import java.io.*; 
import java.util.Scanner;

public class Person 

{

public static void main(String[]args) 

    {

    int age;
    int name;

    Scanner scan = new Scanner(System.in);

    System.out.println("Enter in your age.");
    age = scan.nextInt();

     if (age < 18) 

     {
         System.out.println("So you're a kid, huh? That's fine.");
     } 

     else if (age >= 18)

     {
        System.out.println("Ah, and adult! Good.");
     }

     @SuppressWarnings("resource")
     Scanner in = new Scanner(System.in);

     System.out.println("Enter in your name");
     name = in.nextInt();

     System.out.println("So you're " + age + " years old and your name is " + name);


}
}

Advertisement

Answer

Issues

 int name; //Name should be of type String
 ...
 System.out.println("Enter in your name");
 name = in.nextInt(); //It doesn't handle the string since your using `nextInt`

Solution

 String name;
 ...
 System.out.println("Enter in your name");
 name = in.nextLine();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement