java吧 关注:1,233,515贴子:12,701,596
  • 2回复贴,共1

请教一下各位高手,这是我同学的一个疑问

只看楼主收藏回复

package chpt05;
import java.util.Scanner;
public class hw05 {
public static void main(String[] agrs) {
Scanner input = new Scanner(System.in);
int number = 0;
boolean isRight = true;
do {
System.out.print("请输入数字1-7(输入0结束):");
if (input.hasNextInt() == true) {
number = input.nextInt();
switch (number) {
case 1:
System.out.println("MON");
isRight = false;
break;
case 2:
System.out.println("TUR");
isRight = false;
break;
case 3:
System.out.println("WED");
isRight = false;
break;
case 4:
System.out.println("THU");
isRight = false;
break;
case 5:
System.out.println("FRI");
isRight = false;
break;
case 6:
System.out.println("SAT");
isRight = false;
break;
case 7:
System.out.println("SUN");
isRight = false;
break;
case 0:
System.out.println("程序结束");
break;
default:
System.out.print("您输入的是无效数字,请重新输入:");
number = input.nextInt();
isRight = false;
}
} else {
System.out.println("请输入有效数字:");
number = input.nextInt();
isRight = false;
}
} while (!isRight);
}
}
编写完成不会报错
他为了检测错误
在循环中加入了一个hasNextInt()==true/
实际运行效果:
请输入数字1-7 (输入0结束):a //若输入字符a
Exception in thread "main" java.util.InputMismatchException
请输入有效数字:
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at chap05.hw.syl.text.main(text.java:58)


IP属地:上海1楼2014-05-05 22:30回复
    输入不匹配异常


    IP属地:江苏2楼2014-05-05 23:21
    回复