如何指定输入

时间:2013-04-12 13:34:19

标签: java

请在此代码中帮助指定仅对整数的输入 .................................................. ..............

        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

3 个答案:

答案 0 :(得分:2)

如果唯一有效的输入是12,那么我只会限制这些确切的字符 (编辑:这已经过测试并且有效):

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);
}

答案 1 :(得分: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

答案 2 :(得分: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");
        }     
    }