'Stuck in loop after entering any other datatype in place of int
Can anyone please tell me what is wrong with the code. I am stuck in a loop after entering any other datatype in place of int.
I am trying to make this program so if i enter any other datatype than the datatype which is mentioned i will get a message and the program will ask me again to enter the code.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Integer i=null;
int j=0;
Scanner sc = new Scanner(System.in);
while(j==0) {
i=0;
try {
i = sc.nextInt();
System.out.println(i);
if(i>=0||i<=0){
break;
}
} catch (Exception e) {
System.out.println("Please enter only integers!");
}
}
}
}
Solution 1:[1]
Here is a solution :-
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
try {
System.out.println(sc.nextInt());
break;
} catch (Exception e) {
System.out.println("Please enter only integers!");
sc.nextLine();
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LeNan18 |
