我正在尝试使用简单的cmd行计算器打印出“错误的输入:”加上带有变量的数字,即在args []中找到的“4x”。我已经尝试过无法实现RegEx,现在我正在尝试使用Patter和Matcher库来解决它。我认为可能使用“stringMatch.find(element)”会起作用,但“element”无法放在方法find()中。任何帮助表示赞赏..
public class Calculator {
public static void main(String[] args) {
//check number of strings passed
if (args.length != 3) {
System.out.println("usage: java Calculator operand1 operator operand2");
System.exit(0);
}
//result of the operation
int result =0;
Pattern stringPat = Pattern.compile("\\d");
Matcher stringMatch = stringPat.matcher("");
//determine the operator
try{
switch (args[1].charAt(0)) {
case '+':
result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
break;
case '-':
result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
break;
case '*':
result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
break;
case '/':
result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
break;
}
} catch (NumberFormatException e) {
for(String element: args)
if (stringMatch.find()){
System.out.println("Wrong Input: " + element);
System.exit(0);
}
}
//display result
System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
}
}
答案 0 :(得分:1)
为了保持逻辑简洁,在到达交换机之前进行有效值检查可能会更好,如果通过则继续。看看我下面的示例解决方案,并尝试跟踪逻辑。您可以使用try...catch
块来捕获解析错误,这意味着传入了无效的整数。
public static void main(String[] args) {
if (args.length != 3) {
System.out.println("usage: java Calculator operand1 operator operand2");
return;
}
Integer firstValue;
Integer secondValue;
try {
firstValue = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("Invalid value:" + args[0]);
return;
}
try {
secondValue = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println("Invalid value:" + args[2]);
return;
}
char operator = args[1].charAt(0);
int result;
switch (operator) {
case '+':
result = Math.addExact(firstValue, secondValue);
break;
case '-':
result = Math.subtractExact(firstValue, secondValue);
break;
case '*':
result = Math.multiplyExact(firstValue, secondValue);
break;
case '/':
result = Math.floorDiv(firstValue, secondValue);
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
}
如果您对我所做的任何事情有任何疑问或需要澄清,请随时回复此帖子,我会尽力帮助您:)