Java: How to test if an input is a double or an int

五迷三道 提交于 2019-12-13 21:03:48

问题


I have a do while loop. Checking x is between two values. Now im supposed to be taking in an int value, but if the user types a double im getting exceptions. How do I incorparate a check in the same if statement so that if the user types a double it would print something like "x must be an int between 10 and 150:"

            do {
            x = sc.nextInt();
            if ( x < 10 || x > 150 ) {
                System.out.print("x between 10 and 150: ");
            } else {
                break;
            }

回答1:


You can just catch the exception and handle it, using a while (true) to allow the user to re-try.

Here's my code:

Scanner sc = new Scanner(System.in);
do {
    System.out.print("\nInsert a number >>> ");
    try {
        int x = sc.nextInt();
        System.out.println("You inserted " + x);
        if (x > 10 && x < 150) {
            System.out.print("x between 10 and 150: ");
        } else {
            break;
        }
    } catch (InputMismatchException e) {
        System.out.println("x must be an int between 10 and 150");
        sc.nextLine(); //This line is really important, without it you'll have an endless loop as the sc.nextInt() would be skipped. For more infos, see this answer http://stackoverflow.com/a/8043307/1094430
    }
} while (true);



回答2:


You do not need an additional check. The exception is just there so you can act accordingly in your program. After all, it doesn't really matter how exactly the input was wrong. Just catch the exception (NumberFormatException, I guess?) and upon catching it, print an error message:

while (true) try {
    // here goes your code that pretends only valid inputs can occur
    break;   // or better yet, put this in a method and return
} catch (NumberFormatException nfex) {  // or whatever is appropriate
    System.err.println("You're supposed to enter integral values.");
    // will repeat due to while above
}



回答3:


public class SomeClass {                                                         
    public static void main(String args[]) {                                     
        double x = 150.999; // 1
        /* int x = (int) 150.999; */ // 2                                          
        if ( x >= 10 && x <= 150 ) { // The comparison will still work                                             
            System.out.print("x between 10 and 150: " + x + "\n");               
        }                                                                        
    }                                                                            
}
  1. Declare x as double, comparisons between double and int will still work.
  2. Or, cast the number and any decimal values will be discarded.


来源:https://stackoverflow.com/questions/19816013/java-how-to-test-if-an-input-is-a-double-or-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!