I want to show my own error to the screen insted of this ==>
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:964)
at java.base/java.util.Scanner.next(Scanner.java:1619)
at java.base/java.util.Scanner.nextInt(Scanner.java:2284)
at java.base/java.util.Scanner.nextInt(Scanner.java:2238)
I want it like this if input enters a str or – number ==>
Please enter a valid number!
I tried this but it is not working but at least it’s working for nil or – numbers but when I enter a string nothing is working
import java.util.Scanner;
class Main {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int firstNum = scanner.nextInt();
int secondNum = scanner.nextInt();
if(secondNum == 0 || firstNum == 0){
System.out.print("Please enter a valid number!");
} else if(firstNum > 0 && secondNum > 0){
int add = Math.addExact(firstNum,secondNum);
System.out.print(add);
} else{
System.out.print("Please enter a valid number!");
}
}
}
New contributor
Shoxrux Atabayev is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.