【问题标题】:How to know the number is a double如何知道数字是双
【发布时间】:2018-07-04 22:54:38
【问题描述】:

我在 Java 中编写了一些代码,查看被归为字符串的内容,然后将该字符串转换为 double 或 int IF 找到一个小数(句点)。在我的代码中,它总是跳出循环并打印“找不到数字”。这是为什么?怎么了。

我的代码:

//check if its actually numbers
if(leftSide.matches("[0-9]+") && rightSide.matches("[0-9]+")){
    System.out.println("numbers found");

    if(leftSide.contains(".") || rightSide.contains(".")){
        System.out.println("convert to doubles");
    }else{
        System.out.println("convert to ints");
    }
}else{
    System.out.println("no numbers found");
}

【问题讨论】:

  • 你为什么不用try/catch来做呢?
  • 尝试调试您的代码? String.matches 也将评估整个字符串。
  • 请阅读此帮助页面:stackoverflow.com/help/mcve
  • leftSiderightSide 是如何实例化的?
  • 这部分代码:if(leftSide.matches("[0-9]+") && rightSide.matches("[0-9]+")) 与下面的相矛盾: if(leftSide.contains(".") || rightSide.contains(".")){

标签: java string if-statement int double


【解决方案1】:

您想检查StringDoubleInteger 还是不是,是吗?

我会这样做:

public class Demo{

    public static void main(String [] args) {
        String str = "54.45k";

        double num;

        try {
            num = Double.parseDouble(str);
            if((num == Math.floor(num)) && !Double.isInfinite(num)) {
                System.out.println("String is an Integer!");
            }else {
                System.out.println("String is a Double!");
            }
        } catch(Exception e) {
            System.out.println("String isn't an Integer or a Double!");
        }
    }
}

我试过了,效果很好!

【讨论】:

  • 是的......好吧,我想检查字符串中是否有句点......这意味着用户正在使用十进制数字。如果是这样,请使用转换为双精度的字符串进行数学运算。如果不是,则将字符串转换为整数。
猜你喜欢
  • 2012-08-17
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-26
  • 1970-01-01
相关资源
最近更新 更多