Here we are a program to check if input is an integer or character in Java.
- Take input integer, character or any other data from user.
- Inside checkData() method, we iterate the user input through the for loop.
- In first If (str.charAt(i) >= ‘A’ || str.charAt(i) >= ‘a’) block it check it user input is character and store in String s1 parameter.
- In second else If (str.charAt(i) >= ‘0’ && str.charAt(i) <= ‘9’) block it check user input is number and store in String s1 parameter.
- In third else block it check, if user input is not an integer or character and store in String s1 parameter.
- Now Print the String s2 as an output value.
import java.util.Scanner;
public class CheckIntChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input value : ");
String str = sc.next();
System.out.println(checkData(str));
}
public static String checkData(String str) {
String s1 = "";
String s2 = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) >= 'A' || str.charAt(i) >= 'a') {
s1 = s1 + str.charAt(i);
s2 = "it is character and value is:- " + s1;
} else if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
s1 = s1 + str.charAt(i);
s2 = "it is integer and value is:- " + s1;
} else {
s2 = "this is not a character and number";
}
}
return s2;
}
}
Output :-
Enter input value :
@#
this is not a character and number