gpt4 book ai didi

java - NumbeFormatException 问题

转载 作者:行者123 更新时间:2023-12-02 12:11:57 24 4
gpt4 key购买 nike

我正在尝试使用一个简单的命令行计算器打印出“错误输入:”加上在 args[] 中找到的变量数字,即“4x”。我已经尝试将 RegEx 实现为 no avial,现在我尝试使用 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);
}
}

最佳答案

为了保持逻辑简洁,最好在到达开关之前进行有效值检查,如果通过则继续。看看下面我的示例解决方案并尝试追踪逻辑。您可以使用 try...catch block 来捕获解析错误,这意味着传入了无效的整数。

  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);
}

如果您对我所做的任何事情有任何疑问或需要澄清,请随时回复这篇文章,我会尽力帮助您:)

关于java - NumbeFormatException 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46473042/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com