Java:如何测试输入是双精度还是整数 [英] Java: How to test if an input is a double or an int

查看:401
本文介绍了Java:如何测试输入是双精度还是整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个do while循环。检查x在两个值之间。现在im应该采取一个int值,但如果用户键入双重获取异常。如何在同一个if语句中重合检查,以便如果用户键入一个double,它将打印像x必须是一个介于10和150之间的int:

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;
            }


推荐答案

并处理它,使用 while(true)允许用户重试。

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

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);

这篇关于Java:如何测试输入是双精度还是整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆