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

22nd May 2021, 3:09 AM
Azalea
10 Réponses
+ 4
BY KEEPING AN EYE ON HIM [LOL]
23rd May 2021, 5:06 AM
NEZ
NEZ - avatar
+ 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("...");
22nd May 2021, 3:13 AM
Deyzze
Deyzze - avatar
+ 2
If you want to keep asking the user to input values until it's an integer - https://code.sololearn.com/cEMHpsL4XRBy/?ref=app
22nd May 2021, 3:19 AM
Soumik
Soumik - avatar
+ 2
Azalea java.util.Scanner and java.util.InputMismatchException classes.
22nd May 2021, 3:26 AM
Soumik
Soumik - avatar
+ 1
Soumik [Busy] what certain package do i need to import?😅
22nd May 2021, 3:24 AM
Azalea
22nd May 2021, 4:09 AM
Azalea
+ 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
22nd May 2021, 4:12 PM
6hpxq9
6hpxq9 - avatar
0
Soumik [Busy] what is the " ex" for in catch(InputMismatchException ex)?
22nd May 2021, 3:53 AM
Azalea
0
Azalea ex is an object of InputMismatchException . It can be anything like a, b, c, e
22nd May 2021, 4:07 AM
A͢J
A͢J - avatar