使用扫描仪帮助输入

时间:2011-09-09 10:06:38

标签: java exception input java.util.scanner

public int Remove(int i, Briefcase c[], String[] m) {

        int nChoice = 0;
        boolean inputisok = false;

        while (inputisok == false) {
            System.out.print("\tPlease remove " + i + " cases: ");
            nChoice = input.nextInt();
            if (c[nChoice] == null || nChoice < 0 && nChoice >= c.length) {
                System.out.println();
                System.out.println("\tInvalid Input please Try again\n");
            } else {
                System.out.println("\tI'm " + m[nChoice]
                        + " You just removed case # " + nChoice);
                System.out.println("\t|" + nChoice + "| contains $"
                        + c[nChoice].getAmount() + "\n");
                inputisok = true;
            }
        }
        return nChoice;
    }

我的问题是,当我输入一个字母和一个负数,或一个高于27的数字时,我总是会收到异常错误,我该如何解决?

2 个答案:

答案 0 :(得分:0)

以下行不正确:

if (c[nChoice] == null || nChoice < 0 && nChoice >= c.length) {

你想改变它:

if (nChoice < 0 || nChoice >= c.length || c[nChoice] == null) {

有两处变化:(1)&&成为||; (2)条款已经重新订购。

(1)&&错误,因为nChoice < 0 && nChoice >= c.length始终评估为false,因为nChoice不能同时小于零且大于c.length (谢谢,@ Aleks G!)

(2)在原始版本中,您尝试访问c[nChoice],然后确保nChoicec的范围内。如果不是,这将导致ArrayIndexOutOfBoundsException而不是打印出“输入无效”。

Short-circuit evaluation是条款排序重要的原因。

最后,在从input读取之前,您可以调用hasNextInt()以确保下一个标记可以解释为有效整数。

答案 1 :(得分:0)

使用hasNextInt()方法:

public int Remove(int i, Briefcase c[], String[] m) {

    boolean isNextIntCorrect = false;
    int enteredInt;

    while(!isNextIntCorrect){
        System.out.println("\tPlease remove " + i + " cases: ");
        Scanner inputScanner = new Scanner(input.next());
        if(inputScanner.hasNextInt()){
            enteredInt = inputScanner.nextInt();
            isNextIntCorrect = enteredInt >= 0 && enteredInt < c.length 
                && enteredInt < m.length)
        }
        inputScanner.close();

        if(!isNextIntCorrect){
            System.out.println("\tInvalid Input please Try again\n");
        }
    }
    System.out.println("\tI'm " + m[enteredInt]
                    + " You just removed case # " + enteredInt);
    System.out.println("\t|" + enteredInt+ "| contains $"
                    + c[enteredInt].getAmount() + "\n");
}

这样您就可以确定处理正确的 int!