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

标签 java if-statement casting

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

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

最佳答案

您不需要额外的支票。异常(exception)就在那里,因此您可以在程序中采取相应的操作。毕竟,输入错误的具体程度并不重要。只需捕获异常(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
}

关于Java:如何测试输入是 double 还是 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19816013/

相关文章:

javascript - 使用一个脚本同时打开多个页面

c# - 将对象转换到 T

java - Spring Mongotemplate从多个集合中获取数据

java - 如何在 REST Web 服务中接收大型 XML 文件

java - 第一人称相机胶卷

c# - 将 .txt 文件解析为不同的数据类型

java - 如何转换 hashmap.values().toArray() ,其中这些 value() 也是 HashMap ?

java - 使用 postman 测试启用 spring security 的 api

python-3.x - 遍历列表字典并更新相应的列 - pandas

javascript - 比较提示中的 userInput 时简化 IF 语句