有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

if语句Java:如何测试输入是double还是int

我有一个做循环。检查x是否在两个值之间。现在,我应该接受一个int值,但是如果用户键入一个double,我就会得到异常。我如何在同一if语句中输入一个检查,以便如果用户键入double,它将打印类似“x必须是介于10和150之间的整数”:

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

共 (3) 个答案

  1. # 1 楼答案

    您可以捕获异常并处理它,使用while (true)允许用户重试

    这是我的密码:

    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. # 2 楼答案

    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. 将x声明为double,double和int之间的比较仍然有效
    2. 或者,强制转换数字,任何十进制值都将被丢弃
  3. # 3 楼答案

    您不需要额外的支票。异常就在那里,因此您可以在程序中相应地执行操作。毕竟,输入错误的程度并不重要。只需捕获异常(我想是NumberFormatException吧?)捕获后,打印一条错误消息:

    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
    }