Strange behaviour in Scanner with negative numbers in java
i try to find the answer but could not, maybe is a litlle strange what im going to ask, and i would like to get some idea of what is going wrong here. (Sorry for my english, its a litlle poor but i'll do my best)
This is the deal, i'm using a method to return an int in java, the method uses try catch to avoid the program to explode (please, note that im just starting whith programming and java)
well, this metod uses try catch like this:
public int safeEnter(String message, int min, int max) {
/**
* This method takes some parameters and validates the true enter of an int
* inside some ranges
*/
int aux;
String auxInt;
do {
auxInt = input.nextLine().trim();
try {
aux = Integer.parseInt(auxInt);
} catch (NumberFormatException ex) {
System.out.println("Enter a " + message + " between " + min + " & " + max);
aux = Integer.MIN_VALUE;
开发者_JS百科 }
}
while(aux < min || aux > max);
return aux;
}
(All this code has been traduced to english ^.^)
Weel, the problem is using this method like this:
int month = safeEnter("month", 1, 12);
this will validate the problem if i give it a char or a word instead of an int, and will ask for an int again, this works actually prety as planed, but if i give this a negative number i should give 2 enter before it to show the message and ask for the number again, this wont hapenn if i give it a char string or an int between ranges or out ranges but beeing positive.
What do you think could be the problem here? cause i "think" it just okay, something about Scanner that i should know or i'm missing??
Best, Mauricio
negative numbers are valid integers and do not throw the NumberFormatException. hence, your loop condition evaluates to true, and your do-while loop executes again, and your Scanner asks for input again.
you can try the following:
Scanner input = new Scanner(System.in);
while(true) {
try {
auxInt = input.nextLine().trim();
aux = Integer.parseInt(auxInt);
if(aux >= min & aux <= max)
break;
System.out.println("Enter a " + message + " between " + min + " & " + max);
} catch (NumberFormatException ex) {
System.out.println("Enter a " + message + " between " + min + " & " + max);
}
精彩评论