简体   繁体   中英

Java - Error message InputMismatchException

so I was working on a program for school in Java and I am using Eclipse on mac osx. When I run the program it gives me this error:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Dank.main(Dank.java:13)

This is the code:

             import java.util.Scanner;
             public class Dank
           {
 static Scanner in = new Scanner(System.in);
 public static void main(String args[])
{
int antonio='0';
int answer;
System.out.print("Whats your name? ");
answer = in.nextInt();
if (answer == antonio) {
    System.out.println("are you sure? you are a Dank Meme "+answer);
}
else
{
        System.out.println("Damn, you aren't a Dank Meme "+answer);
}
  }
  }

the in.nextInt() only allowing integer as an input. So if you input a string it will give you inputmismatchexception. try to change it to in.nextLine(). your condition earlier. it doesn't read '0' as 0. the program reads it as character of '0' so it returns 48 because you gave it to an int. try to use this code.

 public class TestClass {


 static Scanner in = new Scanner(System.in);
public static void main(String args[])
{
String antonio = "0";
String answer;

System.out.print("Whats your name? ");
answer = in.nextLine();
if (answer .equalsIgnoreCase(antonio) ) {
System.out.println("are you sure? you are a Dank Meme "+answer);
}
else
{
 System.out.println("Damn, you aren't a Dank Meme "+answer);
}
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM