题目是这样的:
Write a code segment to prompt the user to input an integer between 0 and 100 (inclusive) and keep prompting the user until he does so. Verify both the integer data type entered and the range.要求写一个循环要求用户输入一个介于0-100的整数,验证输入为整形和数据区间,直到用户输入正确数据位置。
我写的代码,有两个问题,一个是如果第一次输入的是小数,那会进入异常处理,可是如果继续输入小数,那JAVA就处理不了了,然后就会出错。怎么才能改进达到要求呢?谢谢!import java.util.*;
public class Input {
public static void  main(String[] args){
Scanner input= new Scanner(System.in);
boolean finish=true;
int i=-1;
while(finish){
try{
System.out.println("Input an integer between 0 and 100:");
i=input.nextInt();
if(i>100||i<0){
System.out.println("Number input need to between 0 and 100");
}
else{
finish=false;
}
}
catch(InputMismatchException ime)
{
Scanner input2=new Scanner(System.in);
System.out.println("Number format is wrong.");
System.out.println("Input an integer between 0 and 100:");
i=input2.nextInt();
finish=false;
}
}
}
}

解决方案 »

  1.   

    package test_1;import java.util.*;public class Input {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean finish = true;
    int i = -1;
    System.out.println("Input an integer between 0 and 100:");
    while (finish) {
    try {

    i = input.nextInt();
    if (i > 100 || i < 0) {
    System.out.println("Number input need to between 0 and 100");
    } else {
    finish = false;
    }
    } catch (InputMismatchException ime) {
     input = new Scanner(System.in);
    System.out.println("Number format is wrong.");
    System.out.println("Input an integer between 0 and 100:");

    // i = input2.nextInt();
    // finish = false;
    }

    }
    }
    }
      

  2.   

    1楼的修改是正确的。
    lz,你错误的原因就在于,你没有对在catch块里面写的  i = input.nextInt(); ,所以导致了你所说的,当再次输入小数时,会因为无法处理而退出,实际就是因为,你再次输入的信息是由catch 块里面的input获得的,此时如果出现输入类型异常,就没有catch 来捕获它了。
      

  3.   

    catch是捕获异常用的,最后两句放进去是啥意思撒
      

  4.   

    我试了一楼的做法..死循环啊..为什么呢?
    死循环输出如下
    Number format is wrong.
    Input an integer between 0 and 100:
    Input an integer between 0 and 100:
      

  5.   

    你直接复制代码试试   我这里是正确的Input an integer between 0 and 100:
    1.1
    Number format is wrong.
    Input an integer between 0 and 100:
    1.1
    Number format is wrong.
    Input an integer between 0 and 100:
    2