i want to ask the user to input a number between 0 and 180. but the variable has to be a String.
// Saisie du nombre de jours de location
System.out.println("Entrez le nombre de jours de location (supérieur à 0 et inférieur ou égal à 180) : ");
nbJoursLouer = Clavier.lireString();
while ( nbJoursLouer < "0" || nbJoursLouer > "180") {
System.out.println("Entrée invalide !");
System.out.println("Entrez le nombre de jours de location (supérieur à 0 et inférieur ou égal à 180) : ");
nbJoursLouer = Clavier.lireString();
}
when i run and input a letter instead of a number, i get this message:
Entrez le nombre de jours de location (supérieur à 0 et inférieur ou égal à 180) :
d
Exception in thread "main" java.lang.NumberFormatException: For input string: "d"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at Tp1.main(Tp1.java:100)
CodePudding user response:
You can not use <
and >
for String in Java, it's a compile error. The closest equivalent is String.compareTo(String)
, which won't work how you intend it to: "100" would be less than "18" because strings are ordered lexicographically and Java won't try to be "smart" like JavaScript. Hence, you must convert your string to integers explicitly. Have a look at this related question for how to use Integer.parseInt()
.
The error message you shared shows that Integer.parseInt()
is used somewhere. It tries to convert the string to a number by reading it character by character. But when it encounters a character that is invalid for integers (letters, special characters...), it will fail with the exceptions you are seeing. By using a try-catch
clause, you can react to that and handle it by returning an error message similar to the one in your code.
int lireNombre() {
while (true) {
System.out.println("Entrez le nombre de jours de location (supérieur à 0 et inférieur ou égal à 180) : ");
try {
int value = Integer.parseInt(Clavier.lireString());
if (value > 0 || value <= 180) {
return value;
} else {
System.out.println("Ce n'est pas supérieur à 0 et inférieur ou égal à 180!");
}
} catch (NumberFormatException e) {
System.out.println("Ce n'est pas un nombre!");
}
}
throw new RuntimeException("We should never have gotten here");
}
CodePudding user response:
u must convert String to an Integer
Integer n = Integer.valueOf(nbJoursLouer);
while ( n < 0 || n > 180)
the nbJoursLouer variable is not a number
it's just the letter "d"
Your code is wrong.