+ 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

18th Jan 2019, 6:41 AM
Jaydenbird
Jaydenbird - avatar
7 odpowiedzi
+ 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.
18th Jan 2019, 6:54 AM
Umar Sunusi Maitalata
Umar Sunusi Maitalata - avatar
+ 3
use this to check for integer input if(KeyBd. hasNextInt() ) { input = KeyBd. nextInt() ; } else { System.out.println("your message" ) ; }
18th Jan 2019, 7:04 AM
Azeddine Hamdaoui
Azeddine Hamdaoui - avatar
0
You are storing the variable as int, so you can't store in it string.
18th Jan 2019, 6:52 AM
Maneren
Maneren - avatar
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/
18th Jan 2019, 6:55 AM
Denise Roßberg
Denise Roßberg - avatar
0
Yogesh But your program don't solve the problem if the input is String.
19th Jan 2019, 5:30 AM
Denise Roßberg
Denise Roßberg - avatar
0
Норм
7th Mar 2019, 10:43 AM
Petimat Barkinhoeva
Petimat Barkinhoeva - avatar
0
Норм делаем программу
7th Mar 2019, 10:44 AM
Petimat Barkinhoeva
Petimat Barkinhoeva - avatar