+ 3

can any code check whether the input is integer or a String in Scanner

any code ?

22nd Sep 2017, 4:34 AM
Raghav Khullar
Raghav Khullar - avatar
8 Réponses
+ 2
import java.util.Scanner ; public class c{ public static void main(String[ ] args) { Scanner n = new Scanner(System.in); char c =n.next().charAt(0); if(Character.isDigit(c)){ System.out.println("It's number"); } else if(Character.isLetter(c)){ System.out.println("It's letter"); } else System.out.println("It's symbol"); } }
11th Oct 2017, 2:27 PM
Gaurav Nagar
Gaurav Nagar - avatar
+ 8
So here's what I did. Instead of using Scanner.nextInt() I used a simple next() to keep the information and not loose it. This means that I can use it again if needed. Then I test each value if it can convert to an Integer, if so then it's a number, else it's just a string https://code.sololearn.com/cMqAN0Xa2mNB/?ref=app
22nd Sep 2017, 5:13 AM
Limitless
Limitless - avatar
+ 5
Well, there are methods for that in java. If you write sc.nextInt() it will get an integer type, and if you type sc.nextLine() it will get a string
22nd Sep 2017, 5:14 AM
Saidmamad Gulomshoev
Saidmamad Gulomshoev - avatar
+ 4
Indeed,the problem is when we use scan.nextInt() and it throws an exception, you lose that data
22nd Sep 2017, 5:25 AM
Limitless
Limitless - avatar
+ 3
java
22nd Sep 2017, 4:57 AM
Raghav Khullar
Raghav Khullar - avatar
+ 3
nice, so then you just plug that into a for loop and test each character, if all characters are digits, then it's an Integer
11th Oct 2017, 3:13 PM
Limitless
Limitless - avatar
+ 2
yes .isDigit() and .isLetter() method of character using array code can easily do this
11th Oct 2017, 1:11 PM
Gaurav Nagar
Gaurav Nagar - avatar
+ 1
in which language?
22nd Sep 2017, 4:44 AM
sayan chandra
sayan chandra - avatar