简体   繁体   English

Java - 错误消息 InputMismatchException

[英]Java - Error message InputMismatchException

so I was working on a program for school in Java and I am using Eclipse on mac osx.所以我正在用 Java 为学校开发一个程序,我在 mac osx 上使用 Eclipse。 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. in.nextInt() 只允许整数作为输入。 So if you input a string it will give you inputmismatchexception.所以如果你输入一个字符串,它会给你 inputmismatchexception。 try to change it to in.nextLine().尝试将其更改为 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.它不会将“0”读作 0。程序将其读作“0”的字符,因此它返回 48,因为您将其赋予了 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);
}
}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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