将double格式化为函数参数

问题描述

我有一个函数,它接受一个double作为参数。但是,如果在调用函数时输入“ 8”,则该过程将作为“ 8.0”处理。

我知道我可以使用String.format()和其他方法对其进行格式化,但是输入数字的格式对于结果很重要(8与8.0的结果不同,并且我不知道用户想要的功能主体)。

我知道我可以添加格式参数以及双精度function(double d,DecimalFormat f),但这将使它使用起来更加繁琐,并且无论如何它都打算用作util函数。有提示吗?

解决方法

根据您的问题,有一些方法可以解决此问题。

  1. 方法重载

如果用户输入是通过代码输入的,则可以使用相同的方法名称来处理不同的类型。

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
    }
}
  1. 处理字符串

但是,例如,如果用户输入是通过键盘输入的,则可以使用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
        }
    }
}