I've implemented a method that asks the user to enter a value. If said value is out of range or it isn't the correct type of value, it should show an error message and then ask again.
public static Integer getValue (Integer minValue, Integer maxValue) {
Scanner input;
input = new Scanner (System.in);
Integer value;
value = null;
while (true) {
try {
value = input.nextInt();
input.nextLine();
if ((value >= minValue) && (value <= maxValue)) {
break;
} else {
// Shows message that says value is not in range.
continue;
}
} catch (InputMismatchException IME) {
// Shows message that says value is not an integer.
input.next();
continue;
}
}
input.close();
return(value);
}
The code can identify correctly when it's being given an undesired value. The problem comes when the value is actually correct, then it just hangs and takes me to the debugger.
This is an example of an execution:
Select the type of furniture:
1. - Dresser.
2. - Shelf.
3. - Rectangular table.
4. - Round table.
You chose: abc // Asks again because the value entered is not int.
a b c
adsf
5 // Asks again because the value entered is not in range.
1 // Here it is when the compiler takes me to the debugger.
Here's what happens if i force the execution past this point; it shows me the menu below then it completely crashes after asking the user for another value:
Select the type of wood.
1. - Mahogamy.
2. - Cherry-tree.
3. - Walnut.
4. - Pine tree.
5. - Oak tree.
You chose: Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
This is how it's being called from main:
furnitureMenu();
indexTree = getValue(minIndexFurniture, maxIndexFurniture);
woodMenu();
indexWood = getValue(minIndexWood, maxIndexWood);
It's crucial that I get this method to work because, as shown above, I'll require an input from the user several other times, and not just to select from menus, but also to get specifications for the furniture such as dimensions and what not.
All help is appreciated. Thanks in advance.