6

我正在编写一个需要从键盘输入的程序。我需要输入一个数字,但我不确定它是一个int还是一个double。这是我拥有的代码(针对该特定部分):

import java.io.*;
import java.util.*;

//...
Scanner input  = new Scanner(System.in); 
int choice = input.nextInt();

我知道我可以得到一个Stringand 做parseInt()or parseDouble(),但我不知道它会是哪一个。

4

4 回答 4

5

好吧,整数也是双精度数,因此如果您假设一切都是双精度数,那么您的逻辑就可以了。像这样:

import java.io.*;
import java.util.*;
Scanner input  = new Scanner(System.in); 
double choice = input.nextDouble();

仅当您出于某种原因需要输入为整数时,它才会变得复杂。然后, parseInt() 来测试 int 就可以了。

于 2015-07-26T22:02:08.153 回答
3

double不管它是什么,只要使用它。对整数值使用双精度并没有明显的损失。

Scanner input = new Scanner(System.in); 
double choice = input.nextDouble();

然后,如果您需要知道是否获得了双倍,您可以使用以下命令进行检查Math.floor

if (choice == Math.floor(choice)) {
    int choiceInt = (int) choice);
    // treat it as an int
}

不要乱用catching NumberFormatException,不要在字符串中搜索句点(这甚至可能不正确,例如,如果输入是1e-3双精度 ( 0.001) 但没有句点。只需将其解析为 adouble并移动上。

另外,不要忘记两者nextInt()并且nextDouble() 不要捕获换行符,因此您需要nextLine()在使用它们后用 a 捕获它。

于 2015-07-26T22:56:59.713 回答
0

我要做的是获取String输入,并将其解析为双精度或整数。

String str = input.next();
int i = 0;
double d = 0d;
boolean isInt = false, isDouble = false;

try {
    // If the below method call doesn't throw an exception, we know that it's a valid integer
    i = Integer.parseInt(str);
    isInt = true
}catch(NumberFormatException e){
    try {
        // It wasn't in the right format for an integer, so let's try parsing it as a double
        d = Double.parseDouble(str);
        isDouble = true;
    }catch(NumberFormatException e){
        // An error was thrown when parsing it as a double, so it's neither an int or double
        System.out.println(str + " is neither an int or a double");
    }
}

// isInt and isDouble now store whether or not the input was an int or a double
// Both will be false if it wasn't a valid int or double

这样,您可以确保仅通过解析双精度数不会丢失整数精度(双精度数的可能值范围与整数不同),并且您可以处理既没有输入有效整数也没有输入双精度数的情况。

如果块内的代码抛出异常,try则执行 catch 块中的代码。在我们的例子中,如果方法抛出异常parseInt(),我们会在第二个 try 块所在的 catch 块中执行代码。如果方法抛出异常 parseDouble(),那么我们执行第二个 catch 块内的代码,它会打印一条错误消息。

于 2015-07-26T22:24:45.773 回答
0

You could try using the floor function to check if it is a double. In case you don't know, the floor function basically cuts off any decimal numbers. So you can compare the number with and without the decimal. If they are the same, then the number can be treated as an integer, otherwise a double (assuming you don't need to worry about large numbers like longs).

String choice = input.nextLine();

if (Double.parseDouble(choice) == Math.floor(Double.parseDouble(choice)) {
    //choice is an int
} else {
    //choice is a double
}
于 2015-07-26T22:04:44.050 回答