0
How can I check if a user inputs a char instead of an int?
if the user inputs a char, the program will ask for an input again
10 Respuestas
+ 4
BY KEEPING AN EYE ON HIM [LOL]
+ 3
Scanner n = new Scanner (System.in);
System.out.print("...");
try{
sp = n.nextInt();
} catch(Exception e){
//Display your message here
}
if ( sp != 1 ) {
if ( sp == 2 ) {
System.out.println("...");
}
} else
System.out.println("...");
+ 3
A suggestion:
you should find your question in google first because you will find various answers there.
//
https://stackoverflow.com/questions/21888309/check-for-character-instead-of-integer
https://stackoverflow.com/questions/38277715/how-to-check-if-user-input-is-a-certain-character/38283211
https://www.tutorialspoint.com/how-to-check-if-a-given-character-is-a-number-letter-in-java
+ 2
If you want to keep asking the user to input values until it's an integer -
https://code.sololearn.com/cEMHpsL4XRBy/?ref=app
+ 2
Azalea java.util.Scanner and java.util.InputMismatchException classes.
+ 1
Soumik [Busy] what certain package do i need to import?😅
+ 1
🅰🅹 🅐🅝🅐🅝🅣 thanks!!
+ 1
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
while(true)
{
try{
int input = s.nextInt();
break;
}
catch(Exception e){
continue;
}
}
}
}
Here i'm looping until the input be an integer
It is possible because Java gives an error when you try to pass a char input to a int value whitout casting it
0
Soumik [Busy] what is the " ex" for in catch(InputMismatchException ex)?
0
Azalea
ex is an object of InputMismatchException . It can be anything like a, b, c, e