Java: Why Program Skip Char Login?
Java Skip First Character Input When does a program catch an exception?
System.out.println("Enter Character:");
f = s.next().charAt(0);
Program code:
public class Main {
public static void main(String[] args) {
int num;
char f = 'y';
Scanner s = new Scanner(System.in);
do {
try {
System.out.print("Enter Number:");
num = s.nextInt();
catch (InputMismatchException e) {
System.out.println("False=> This is Not Integer");
}
System.out.println("Enter Character:");
f = s.next().charAt(0);
while(f != 'y' && f !='n') {
System.out.println("Press 'y' or 'n'");
f = s.next().charAt(0);
}
}
while(f == 'y');
System.out.print("Print:" + f);
}
}
Compiler output:
Enter Number:ghjgh
False=> This is Not Integer
Enter Character:(Compiler Skip This Input)
Press 'y' or 'n'
n
Print:n
Why is this happening. I don't know why, it is missing input in the catch catch.
+3
user4935991
source
to share
2 answers
Add s.nextLine()
after scanning the number
...
try {
System.out.print("Enter Number:");
num = s.nextInt();
}
catch (InputMismatchException e) {
System.out.println("False=> This is Not Integer");
}
s.nextLine();
...
+1
Nitin dandriyal
source
to share
You can use the instanceof keyword, just like this:
try{
String input = s.nextInt();
int num = Integer.parseInt(input);
// if execute here input is number
}catch(Exception e){
// if execute here input is not number
System.out.println("Please input number!");
}
0
hooks zhang
source
to share