Java 如何读取可能是 int 或 double 的输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31642352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:21:36  来源:igfitidea点击:

How do I read input that could be an int or a double?

javaparsingintegerdoublekeyboard-input

提问by newplayer12132

I'm writing a program in which I need to take input from the keyboard. I need to take a number in, yet I'm not sure if it's an intor a double. Here's the code that I have (for that specific part):

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

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

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

I know I can get a Stringand do parseInt()or parseDouble(), but I don't know which one it'll be.

我知道我可以得到 aString和 doparseInt()parseDouble(),但我不知道它会是哪一个。

采纳答案by durron597

Just use a doubleno matter what it is. There is no noticeableloss on using a double for integral values.

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

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

Then, if you need to know whether you've gotten a double or not, you can check it using Math.floor:

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

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

Don't mess with catching NumberFormatException, don't search the string for a period (which might not even be correct, for example if the input is 1e-3it's a double (0.001) but doesn't have a period. Just parse it as a doubleand move on.

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

Also, don't forget that both nextInt()and nextDouble()do not capture the newline, so you need to capture it with a nextLine()after using them.

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

回答by Paul Sasik

Well, ints are also doubles so if you assume that everything is a double you will be OK with your logic. Like this:

嗯,整数也是双精度数,所以如果你假设一切都是双精度数,那么你的逻辑就可以了。像这样:

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

It only get complex if you needed the input to be an integer for whatever reason. And then, parseInt() to test for int would be just fine.

如果您出于任何原因需要输入为整数,它只会变得复杂。然后, parseInt() 来测试 int 就可以了。

回答by Zarwan

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

您可以尝试使用 floor 函数来检查它是否是双倍。如果您不知道,floor 函数基本上会截断任何十进制数。因此,您可以比较带小数点和不带小数点的数字。如果它们相同,则可以将数字视为整数,否则为双精度(假设您不需要担心像 long 这样的大数字)。

String choice = input.nextLine();

if (Double.parseDouble(choice) == Math.floor(Double.parseDouble(choice)) {
    //choice is an int
} else {
    //choice is a double
}

回答by SamTebbs33

What I would do is get Stringinput, and parse it as either a double or an integer.

我要做的是获取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

This way, you can ensure that you don't lose integer precision by just parsing a double (doubles have a different range of possible values than integers), and you can handle the cases where neither a valid integer or double was entered.

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

If an exception is thrown by the code inside the tryblock, the code in the catch block is executed. In our case, if an exception is thrown by the parseInt()method, we execute the code in the catch block, where the second try-block is. If an exception os thrown by the parseDouble()method, then we execute the code inside the second catch-block, which prints an error message.

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