0

它现在所做的是要求用户输入一个字段编号,但如果用户输入一个非整数,它只会陷入循环并且不会响应用户键入的任何内容。我希望它真正起作用,我认为它在我的 try/catch 中。谢谢

代码:

public static int getFieldNumberFromUser(int maxValue)throws IOException
{
    BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
    String data;
    int fieldNumber;
    boolean isInteger;

    fieldNumber = 0;
    isInteger = false;
    while(isInteger == false)
    {
        System.out.print("Enter a field between 1 and " + maxValue + "(< zero to quit): ");
        data = br.readLine();
        try
        {
            fieldNumber = Integer.parseInt(data);
            isInteger = true;

        }
        catch(NumberFormatException nfe)
        {
            System.out.println("You did not enter a valid integer");
        }
    }
        return fieldNumber - 1;
}
4

2 回答 2

1

您需要在 catch 中退出循环...return -1;在您的 catch 中添加一个。

我不确定你为什么要循环

于 2013-04-02T03:20:57.513 回答
1

检查下面的代码。它似乎工作正常。

    BufferedReader br = new BufferedReader( new InputStreamReader(System.in) );
    String data;
    int fieldNumber;
    boolean isInteger;

    fieldNumber = 0;
    isInteger = false;
    while(isInteger == false)
    {
        System.out.print("Enter a field between 1 and " + maxValue + "(< zero to quit): ");
        data = br.readLine();
        NumberFormatException nfe = new NumberFormatException();
        try
        {
            fieldNumber = Integer.parseInt(data);
            if(fieldNumber > maxValue)
                throw nfe;
            isInteger = true;

        }
        catch(NumberFormatException nfe2)
        {
            System.out.println("You did not enter a valid integer");
        }
    }
        return fieldNumber - 1;
于 2013-04-02T03:34:07.970 回答