2

请在此代码中提供帮助以仅指定整数的输入.......................... …………………………………………………………………………………………

        int shape=0;
        boolean inp=false;
        while (! inp) {
            try 
            {
                shape = (int)(System.in.read()-'0');

            }//try
            catch (IOException e) 
            {
                System.out.println("error");
                System.out.println("Please enter the value again:");
            }//catch
                if ((shape == 1) || (shape == 2)) {
                inp = true;
            }//if
        }//while
4

3 回答 3

2

如果唯一有效的输入是1or2然后我将限制为那些确切的字符(编辑:这已经过测试并且有效):

char c = '-'; //invalid character to default
while (! (c == '1' || c == '2'))
{
   System.out.println("Please enter 1 or 2:");
   c = (char) System.in.read();
   System.out.println(c);
}
于 2013-04-12T13:45:36.540 回答
1

我编辑了答案并输入了完整的代码。它现在可以工作(经过测试)。使用 BufferedReader 可以让您阅读真实的内容Strings(这就是它之前陷入无限循环的原因)

    int shape = 0;
    boolean inp = false;
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    while (!inp) {
        try {
            System.out.println("Type in a number");
            shape = Integer.parseInt(bufferedReader.readLine());  // parse the string explicitly
            System.out.println("thanks");
        }//try
        catch (IOException e) {
            System.out.println("error");
            System.out.println("Please enter the value again:");
        }//catch
        catch (NumberFormatException e) // here you catch the exception if anything but a number was entered
        {
            System.out.println("error");
            System.out.println("Please enter the value again:");
        }//catch
        System.out.println("Shape = " + shape);
        if ((shape == 1) || (shape == 2)) {
            System.out.println("should be true");
            inp = true;
        }//if
于 2013-04-12T13:40:30.903 回答
0
    Integer i = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    while (true)
    {
        System.out.println("Please enter 1 or 2:");
        try {
            i = Integer.parseInt(in.readLine());
            if(i==1 || i==2){
                System.out.println("Success! :)");
                break;
            }
        } catch (IOException ex) {
            System.out.println("IO Exception");
        } catch (NumberFormatException e){
            System.out.println("Invalid input");
        }     
    }
于 2013-04-12T20:25:17.667 回答