读书人

关于在while循环中try,catch语句的有关

发布时间: 2012-09-17 12:06:51 作者: rapoo

关于在while循环中try,catch语句的问题
实现功能是:从控制台输入一个考试的分数,若输入的不是整数,则提示输入错误,继续在输,否则就结束。

具体代码如下:

import java.util.*;

public class SwitchCaseDemo {
public static void main(String[] args) {
int score;
Scanner console = new Scanner(System.in);
boolean isInt=true;
while(true) {
try {
score = console.nextInt();
}
catch (InputMismatchException e) {
isInt=false;
System.out.println("格式不正确,从新再输入:");
}
if(true ==isInt)
break;
}
}
}
但结果是不断的输出“格式不正确,从新再输入”,这是什么原因。该怎么解决呢?

[解决办法]
你对Scanner类的使用还有问题,Scanner类是在循环体之外初始化,你第一次输入的数据没有清空,console类就不会等你再输入新的数据,所以你输入3.1这样非法数据以后的每次getInt都返回3.1,正确的代码可以这样

Java code
import java.util.*;public class SwitchCaseDemo {    public static void main(String[] args) {        int score;        while(true) {            boolean isInt=true;            Scanner console = new Scanner(System.in);            try {                score = console.nextInt();            }catch (InputMismatchException e) {                isInt=false;                System.out.println("格式不正确,从新再输入:");            }            if(isInt)                break;        }    }} 

读书人网 >Java相关

热点推荐