java.util.InputMismatchException 使用 Scanner 和 .nextInt() 时
java.util.InputMismatchException when using Scanner and .nextInt()
我只是想制作一个简单的程序来找点乐子,但我在这里得到了这段代码:
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
public class test5 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(in);
char reply;
reply = (char) keyboard.nextInt();
if (reply == 'y' || reply == 'Y') {
out.println(":-)");
} else {
out.println(":-(");
}
keyboard.close();
}
}
我得到了这个输出:
y
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 test5.main(test5.java:9)
y
和 Y
字符无法转换为 int
,因此出现异常。不幸的是,Scanner
没有 nextChar()
方法,但您可以改用字符串:
String reply = keyboard.next();
if (reply.equalsIgnoreCase("y")) {
out.println(":-)");
} else {
out.println(":-(");
}
我只是想制作一个简单的程序来找点乐子,但我在这里得到了这段代码:
import java.util.Scanner;
import static java.lang.System.in;
import static java.lang.System.out;
public class test5 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(in);
char reply;
reply = (char) keyboard.nextInt();
if (reply == 'y' || reply == 'Y') {
out.println(":-)");
} else {
out.println(":-(");
}
keyboard.close();
}
}
我得到了这个输出:
y
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 test5.main(test5.java:9)
y
和 Y
字符无法转换为 int
,因此出现异常。不幸的是,Scanner
没有 nextChar()
方法,但您可以改用字符串:
String reply = keyboard.next();
if (reply.equalsIgnoreCase("y")) {
out.println(":-)");
} else {
out.println(":-(");
}