首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java相关 >

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

2012-09-17 
关于在while循环中try,catch语句的问题实现功能是:从控制台输入一个考试的分数,若输入的不是整数,则提示输

关于在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;        }    }} 

热点排行