添加try..catch时“输入无法解析”

时间:2013-10-17 21:48:11

标签: java

我最初试图让我的throw语句在没有try catch的情况下工作,并且userInput = input.nextInt();行正常工作。但是当我尝试添加try..catch时,它不喜欢我的输入说它无法解决。我不认为我的try..catch是正确的,但我正在计划解决这个问题后,我可以得到这个输入被识别,但我也很感激你对这些事情的任何反馈。

由于

import java.util.Scanner;

    public class Program6 
    {
        public static void main(String[] args) 
        {
            final int NUMBER_HIGH_LIMIT = 100;
            final int NUMBER_LOW_LIMIT = 10;
            int userInput;

            try
            {
                System.out.print("Enter a number between 10 and 100: ");
                userInput = input.nextInt();//Says input cannot be resolved

                Verify v = new Verify(NUMBER_HIGH_LIMIT, NUMBER_LOW_LIMIT);
            }
            catch(NumberHighException exception)
            {
                userInput = 0;
            }
            catch(NumberLowException exception) 
            {
                userInput = 0;  
            }
        }
    }

1 个答案:

答案 0 :(得分:4)

您需要创建名为input的扫描程序:

public class Program6 {

  public static void main(String[] args) {
    final int NUMBER_HIGH_LIMIT = 100;
    final int NUMBER_LOW_LIMIT = 10;
    int userInput;

    try {
      Scanner input = new Scanner(System.in);
      System.out.print("Enter a number between 10 and 100: ");
      userInput = input.nextInt();//Says input cannot be resolved

      Verify v = new Verify(NUMBER_HIGH_LIMIT, NUMBER_LOW_LIMIT);

    } catch (NumberHighException exception) {
      userInput = 0;
    } catch (NumberLowException exception) {
      userInput = 0;
    }
  }
}