我想用 Java 设计一个程序,它接收两个命令行参数并显示两者的总和,但有一些条件 健康)状况: 1- 如果用户传递“int”中的值,则总和进入“int” 2-如果用户传递“float”中的值,则总和进入“float” 3- 如果用户传递“double”中的值,则 sum 为“double”
注意:不使用if else和switch case
输出类似:
Java 求和 100 50
output - Sum is = 150
java 总和 100 50.99
output - Sum is = 150.99
java 总和
"output - Plz pass 2 command line argument as numbers (0-9) only.
Java 总计 100 次
output - Plz pass 2 command line argument as numbers (0-9) only.
这是我的努力,但我现在不知道该怎么做
class Sum {
public static void main (String args[]){
int a, b, c;
a= Integer.parseInt(args[0]);
b= Integer.parseInt(args [1]);
c= a + b;
System.out.println("Sum is= " +c);
}
最佳答案
您可以使用 BigDecimal
对于任意精度,您可以使用正则表达式来匹配数字。有点像
public static void main(String[] args) {
if (args.length < 2 || !args[0].matches("\\d+[.\\d+]*")
|| !args[1].matches("\\d+[.\\d+]*")) {
System.out.println("Plz pass 2 command line argument as numbers (0-9) only");
return;
}
BigDecimal a = new BigDecimal(args[0]);
BigDecimal b = new BigDecimal(args[1]);
BigDecimal c = a.add(b);
System.out.println("Sum is " + c);
}
关于java - 传递 2 个命令行参数并在 Java 中显示两者的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35679500/