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;
}
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:
You want to change it like so:
There are two changes: (1) the
&&became a||; (2) the clauses have been reordered.(1) The
&&is wrong asnChoice < 0 && nChoice >= c.lengthalways evaluates tofalse, sincenChoicecan’t be simultaneously less than zero and greater thanc.length(Thanks, @Aleks G!)(2) In your original version you try to access
c[nChoice]before making surenChoiceis within the bounds ofc. If it isn’t, this’ll result in anArrayIndexOutOfBoundsExceptioninstead of printing out “Invalid Input”.Short-circuit evaluation is the reason the ordering of clauses matters.
Lastly, before reading from
input, you could callhasNextInt()to make sure that the next token can be interpreted as a valid integer.