I would like to know how to check an input type in java?
- If I input 23 it should say "The input is integer type"
- If 3.0 then "the input is float type"
- If Suman then "The input is string type" etc.
I would like to know how to check an input type in java?
Using regex patterns and the built in Pattern class:
import java.util.Scanner;
import java.util.regex.Pattern;
public class TestClass {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
boolean containsDigit = Pattern.compile("[0-9]").matcher(input).find();
boolean containsNonDigitNonPeriod =
Pattern.compile("[!--/:-~]").matcher(input).find();
int numberOfPeriods = input.replaceAll("[^.]", "").length();
if (containsDigit && !containsNonDigitNonPeriod)
{
if (numberOfPeriods > 1)
System.out.println("A string has been input.");
else if (numberOfPeriods == 1)
System.out.println("A float has been input.");
else
System.out.println("An integer has been input.");
}
else
System.out.println("A string has been input.");
scanner.close();
}
}