开发者

Help with Inputs using 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 &&开发者_StackOverflow中文版; 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;
    }

my problem here is that when I enter a letter and a -negative number, or a number that is higher than 27, I always get an exception error, how do I fix that?


The following line is incorrect:

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

You want to change it like so:

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

There are two changes: (1) the && became a ||; (2) the clauses have been reordered.

(1) The && is wrong as nChoice < 0 && nChoice >= c.length always evaluates to false, since nChoice can't be simultaneously less than zero and greater than c.length (Thanks, @Aleks G!)

(2) In your original version you try to access c[nChoice] before making sure nChoice is within the bounds of c. If it isn't, this'll result in an ArrayIndexOutOfBoundsException instead of printing out "Invalid Input".

Short-circuit evaluation is the reason the ordering of clauses matters.

Lastly, before reading from input, you could call hasNextInt() to make sure that the next token can be interpreted as a valid integer.


Use the hasNextInt() method:

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

This way you are sure of dealing with a correct int!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜