有人可以帮助修复我的功能的逻辑吗?

时间:2013-04-02 03:18:34

标签: java

它现在正在做的是要求用户输入一个字段编号,但是如果用户输入一个非整数,它就会陷入循环并且不会响应用户输入的任何内容。我希望它实际工作,我认为它在我的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;
}

2 个答案:

答案 0 :(得分:1)

您需要退出捕获中的循环...在捕获中添加return -1;

我不确定你为什么要循环

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