+ 4
Else statement not running
Does anyone know how to fix an error that happens when the input is a string? I want that input to trigger the else statement! Thanks! https://code.sololearn.com/c6819kF6kQuY/?ref=app
7 Antworten
+ 5
Because when you are getting the input with nextInt the compiler always expect a number, and as such if you give a string an error will occur. I suggest you get the number as string then convert it to integer to compare it with the 18.
+ 3
use this to check for integer input
if(KeyBd. hasNextInt() ) {
input = KeyBd. nextInt() ;
} else {
System.out.println("your message" ) ;
}
0
You are storing the variable as int, so you can't store in it string.
0
Int input = ...nextInt() --> you have to input a number.
String input = ...nextLine () --> input a String
But in your case I would use try/catch.
int input = 0;
try {
input = keyBd.nextInt ();
} catch (Exception e){
System.out.println ("I'm sorry, I did not unterstand that!")
System.exit (0);
}
The Scanner expects an int number, if not you would get an error. But the code will catch this error (outprint: I did unterstand...) and exit the program.
Edit: https://www.sololearn.com/learn/Java/2175/
0
Yogesh But your program don't solve the problem if the input is String.
0
Норм
0
Норм делаем программу