Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java double Input Validation

Tags:

java

below is the code:

    Scanner scan = new Scanner(System.in);
    String input = scan.next();
    try{
        double isNum = Double.parseDouble(input);
        if(isNum == Math.floor(isNum)) {
            System.out.println("Input is Integer");
             //enter a double again
        }else {
            System.out.println("Input is Double");
            //break
        }
    } catch(Exception e) {
        if(input.toCharArray().length == 1) {
            System.out.println("Input is Character");
             //enter a double again
        }else {
            System.out.println("Input is String");
            //enter a double again
        }
    }

taken from here: how to check the data type validity of user's input (Java Scanner class)

however, when i input 1.0 or 0.0, it is still considered as an integer, is 1.0 not considered a double?

Please help guys, thank you!

like image 586
user3540710 Avatar asked Sep 18 '26 14:09

user3540710


1 Answers

If you want to treat 1.0 as a Double an 1 as an Integer, you need to work with the input variable, which is of type String.

Java will always treat Double x = 1 in the same way as Double y = 1.0 (meaning 1 is a valid Double), so you will not be able to distinguish them with code.

Since you have the original string representation of the input, use a regex or some other validation to check it. For instance a sample regex pattern for double would look like "[0-9]+(\.){0,1}[0-9]*" and for an integer "[0-9]+" or "\d+"

Here is an example:

final static String DOUBLE_PATTERN = "[0-9]+(\.){0,1}[0-9]*";
final static String INTEGER_PATTERN = "\d+";

Scanner scan = new Scanner(System.in);
String input = scan.next();

if (Pattern.matches(INTEGER_PATTERN, input)) {
    System.out.println("Input is Integer");
    //enter a double again
} else if (Pattern.matches(DOUBLE_PATTERN, input)) {
    System.out.println("Input is Double");
    //break
} else {
    System.out.println("Input is not a number");
    if (input.length == 1) {
        System.out.println("Input is a Character");
        //enter a double again
    } else {
        System.out.println("Input is a String");
        //enter a double again
    }
}
like image 185
Ivaylo Slavov Avatar answered Sep 20 '26 04:09

Ivaylo Slavov