Java - 错误消息InputMismatchException

时间:2017-02-09 23:04:28

标签: java

所以我正在研究Java中的学校计划,我在mac osx上使用Eclipse。当我运行程序时,它给了我这个错误:

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)

这是代码:

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

1 个答案:

答案 0 :(得分:0)

in.nextInt()只允许整数作为输入。因此,如果您输入一个字符串,它将为您提供inputmismatchexception。尝试将其更改为in.nextLine()。你早先的病情。它没有读到' 0'为0,程序将其读作' 0'的字符。所以它返回48因为你把它给了一个int。尝试使用此代码。

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

}