如何使用InputMismatchException来确定输入扫描器的值是否不是整数?基本上,如果他们输入一个单词而不是整数,我需要使用InputMismatchException来返回一条消息。
while (true) {
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
try{
Integer.parseInt(i);
} catch (InputMismatchException e) {
System.out.println("Sorry, " + i + " is not a number.");
}
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
答案 0 :(得分:2)
更改您的代码:
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == 1) {
System.out.println("1 was selected");
} else {
System.out.println("1 was not selected");
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}
}
的变化:
答案 1 :(得分:0)
这就是我的意思
while (true) {
Scanner sc = new Scanner(System.in);
int i = -1;
try
{
i = sc.nextInt();
}
catch (InputMismatchException e)
{System.out.println("Sorry, " + i + " is not a number.");}
if (i == 1)
System.out.println("1 was selected");
else
System.out.println("1 was not selected");
}
答案 2 :(得分:0)
我是编程的新手,我想我得到了你的问题的代码。
while (true) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
try{
int i = Integer.parseInt(s);
if (i == parseInt(i, 3)) {
System.out.println(s+" is selected");
} else {
System.out.println("Input value is " + s);
}
} catch (NumberFormatException e) {
System.out.println("Sorry, " + s + " is not a number.");
}}}
private static int parseInt(int i, int j) {
// TODO Auto-generated method stub
return 0;
}}