Program to Check Input Is an Integer or Character in Java

Here we Check Input is an integer or Character in Java.

  • Take input integer, character or any other data from user.
  • Pass the input String to the checkData() method.
  • Inside the method, iterate through each character of the input using a for loop.
  • In first if (!((ch >= ‘A’ && ch <= ‘Z’) || (ch >= ‘a’ && ch <= ‘z’)) block check whether all characters are alphabetic letters (A-Z or a-z).
  • In second if (!(ch >= ‘0’ && ch <= ‘9’)) block check whether all characters are digits (0-9).
  • If all characters are letters, then the input is a character/string.
  • If all characters are digits, then the input is an integer.
  • Otherwise, it is neither an integer nor a character.
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) {
        boolean isAlphabet = true;
        boolean isDigit = true;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (!((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))) {
                isAlphabet = false;
            }

            if (!(ch >= '0' && ch <= '9')) {
                isDigit = false;
            }
        }

        if (isAlphabet) {
            return "It is a character/string and value is: " + str;
        } else if (isDigit) {
            return "It is an integer and value is: " + str;
        } else {
            return "This is neither an integer nor a character";
        }
    }
}

Output :-
Enter input value :
@#
This is neither an integer nor a character