如何读取可能是int或double的输入? [英] How do I read input that could be an int or a double?

查看:187
本文介绍了如何读取可能是int或double的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 int or a double. Here's the code that I have (for that specific part):

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

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

我知道我可以获得 String 和做 parseInt() parseDouble(),但我不知道它会是哪一个。

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

推荐答案

只要使用 double ,无论它是什么。使用双精度值时,没有明显的损失。

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

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

然后,如果你需要知道你是否已经获得双倍,你可以检查它使用 Math.floor

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

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

不要乱用 catch ing NumberFormatException ,不要搜索字符串一段时间(这可能甚至不正确,例如,如果输入是 1e-3 它是一个双倍的( 0.001 ),但没有句号。只需将其解析为 double 并继续前进。

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-3 it's a double (0.001) but doesn't have a period. Just parse it as a double and move on.

此外,不要忘记两个 nextInt() nextDouble() 不捕获换行符,所以你需要使用后用 nextLine()捕获它。

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.

这篇关于如何读取可能是int或double的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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