日期:2014-05-20  浏览次数:20666 次

请问在此类条件下,如何设定循环条件?
在while do while 以及for 循环结构中,面对如下代码:

Scanner in=new Scanner(System.in);
System.out.print("请输入成绩:");

while (!in.hasNextInt()) //目的:只要不输入整型就无限循环,直到输入正确为止
{
int score= in.nextInt();
System.out.print("请输入数字类型!");
}
System.out.println("输入正确!");

请问如何修改此代码,方可满足上文中的条件?

------解决方案--------------------
Java code

Scanner in = new Scanner(System.in);
        boolean flag = true;
        System.out.print("请输入成绩:");
        while (flag) 
        {    
            String number = in.next();
            if(number.matches("[0-9]*")){
                flag = false;
            } else{
                System.out.println("请输入正确数字类型");
            }
        }

------解决方案--------------------
Java code

        boolean flag = true;
        Scanner in=new Scanner(System.in);
        System.out.print("请输入成绩:");
        while(flag){
            try{
                int score= in.nextInt();
            }catch(Exception e){
                System.out.print("请输入数字类型!");
                in.nextLine();
                continue;
            }
            flag = false;
        }
        System.out.println("输入正确!");