我想用Java设计一个程序,它接收两个命令行参数并显示两者的总和,但有一些条件 健康)状况: 1-如果用户传递“int”中的值,则总和为“int” 2-如果用户传递“float”中的值,则总和为“float” 3-如果用户传递“double”中的值,则总和为“double”
注意:不使用 if else 和 switch case
输出类似:
java Sum 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 Sum 100 jaja
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);
}