英文:
Formatting double as a function parameter
问题
我有一个接受双精度浮点数作为参数的函数。然而,当我调用该函数时,如果我输入“8”,它会被处理为“8.0”。
我知道我可以使用 String.format()
和其他方法来格式化它,然而输入数字的格式对结果很重要(8和8.0具有不同的结果,而在函数体内部,我不知道用户打算输入哪个)。
我知道我可以添加一个格式化参数和双精度浮点数,function(double d, DecimalFormat f)
,但那会使使用变得更加繁琐,而且它本来就被设计为一个实用函数。有什么建议吗?
英文:
I have a function that takes in a double as a paramater. However, if I input "8" when I call the function, it processes as "8.0".
I know that I can format it with String.format()
and other methods, however the format that the number is inputted as is important to the result (8 has a different result than 8.0, and I have no idea inside of the function body which one was intended by the user).
I know that I can add a format parameter as well as the double, function(double d, DecimalFormat f)
, but that would make it much more tedious to use, and it is intended as a util function anyways. Any tips?
答案1
得分: 1
有几种方法可以解决这个问题,取决于你的问题。
- 方法重载
如果用户输入是通过代码提供的,你可以使用相同的方法名处理不同类型。
class Program {
public static void foo(int n) {
// 输入是整数
System.out.println(n);
}
public static void foo(double x) {
// 输入是双精度浮点数
System.out.println(x);
}
public static void main(String[] args) {
foo(8); // 输出 8
foo(8.0); // 输出 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+$")) {
// 输入是双精度浮点数
} else if (input.matches("\\d+")) {
// 输入是整数
} else {
// 输入是其他内容
}
}
}
英文:
There are some ways you can solve this, depending on your problem.
- Method overloading
If the user input is by code, you can handle different types using the same method name.
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
}
}
- Handling strings
However, if the user input is by keyboard, for example, you can use 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
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论