+ 3

How to display a custom error when not entering a defined variable type?

For example if I write the following code: if(age <= 0) { System.out.println("Error"); } else if(age <= 16) { System.out.println("Too Young"); } else if(age < 100) { System.out.println("Welcome!"); } else { System.out.println("Really?"); } If I make an input thing and write -1 there it will show an “Error” string which I defined. But how can I make it to show for instance “Not a number” if I enter letters instead of numbers? Thanks

31st Jan 2018, 3:05 PM
Gosh
2 ответов
+ 8
You may use exception handling for this case. Just catch the error your program yields. For this case, it's InputMismatchException because you input letters instead of integer. Just as an example, import java.util.*; public class Program { public static void main(String[] args) throws InputMismatchException { try { int age = new Scanner(System.in).nextInt(); if(age > 10) System.out.print("Yeah"); } catch(InputMismatchException e) { System.out.print("Not a number"); } } } For more information on exception handling, refer https://www.sololearn.com/learn/Java/2175/
31st Jan 2018, 3:12 PM
Dev
Dev - avatar
0
Thank you, would not figure it out by myself for ages!
31st Jan 2018, 3:23 PM
Gosh