格式化double作为函数参数

aiazj4mn  于 2021-07-04  发布在  Java
关注(0)|答案(1)|浏览(312)

我有一个函数,它把一个double作为参数。但是,如果我在调用函数时输入“8”,它将作为“8.0”处理。
我知道我可以用 String.format() 其他方法,但是输入数字的格式对结果很重要(8的结果与8.0不同,我不知道函数体内部用户想要哪个)。
我知道我可以添加一个格式参数和double, function(double d, DecimalFormat f) ,但这将使它的使用更加繁琐,而且它是作为一个util函数使用的。有什么建议吗?

m0rkklqb

m0rkklqb1#

有一些方法可以解决这个问题,这取决于你的问题。
方法重载
如果用户输入是通过代码进行的,则可以使用相同的方法名处理不同的类型。

class Program {
    public static void foo(int n) {
        // The input is an integer
        System.out.println(n);
    }

    public static void foo(double x) {
        // The input is a double
        System.out.println(x);
    }

    public static void main(String[] args) {
        foo(8); // prints 8
        foo(8.0); // prints 8.0
    }
}

处理字符串
但是,例如,如果用户通过键盘输入,则可以使用regex。

class Program {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String input = s.nextLine();

        if (input.matches("^\\d+\\.\\d+$")) {
            // The input is a double
        } else if (input.matches("\\d+")) {
            // The input is an integer
        } else {
            // The input is something else
        }
    }
}

相关问题