gpt4 book ai didi

java - 代码验证错误

转载 作者:行者123 更新时间:2023-11-30 07:44:23 25 4
gpt4 key购买 nike

我在使用验证代码创建逆波兰表示法计算器时遇到问题。我需要计算器接受两个移位运算符( <<>> )作为计算的一部分。以下代码片段是验证部分和计算部分。

public static boolean isInt(String userinput) {
try {
Integer.parseInt(userinput); // Try to parse. Makes sure that the values entered are actual numbers
return true; // Boolean value to show if the equation entered is valid or not
} catch (NumberFormatException e) {
System.out.println("Please enter a valid expression!");
invalidlines++;
return false;
}
}

public static boolean isValidLine(String line) {
line = line.trim();
if (line.length() <= 4) { // Trims the lines down to 4 and ensures there is no spaces being included
return false;
} else {
String[] calcarray = new String[3];
calcarray = line.split(" ");
String operators = new String("[+\\-\\*\\/\\<<\\>>\\%\\&\\|]"); // Validator using regular expressions to check the operator used
if (isInt(calcarray[0].toString()) && isInt(calcarray[1].toString()) && calcarray[2].matches(operators)) { // Checks that the operator in the string matches the ones in the regular expression
return true;
} else {
return false;
}
}
}

下面是计算器部分:

String keyboardInput = new String();
Scanner kbScan = new Scanner(System.in);
int answer = 0;
while (true) {
display("Please enter an equation");
keyboardInput = kbScan.nextLine();
if (isValidLine(keyboardInput)) {
String[] equation = new String[3]; // We know that this is only going to contain 3 to be valid
equation = keyboardInput.split(" "); // split this up, as it's stored with the spaces.
int num1 = Integer.parseInt(equation[0]);
int num2 = Integer.parseInt(equation[1]);
switch (equation[2]) { // This case switch checks the third position of the
// string to decide which operator is being used. It then works out the
// answer and breaks to the next instruction
case ("+"):
answer = num1 + num2;
break;
case ("-"):
answer = num1 - num2;
break;
case ("/"):
answer = num1 / num2;
break;
case ("*"):
answer = num1 * num2;
break;
case ("<<"):
answer = num1 << num2;
break;
case (">>"):
answer = num1 >> num2;
break;
case ("%"):
answer = num1 % num2;
break;
case ("|"):
answer = num1 | num2;
break;
case ("&"):
answer = num1 & num2;
break;
}
display("Your post fix expression: " + equation[0] + " " + equation[1] + " " + equation[2]);
display("Your calculation: " + equation[0] + " " + equation[2] + " " + equation[1] + " = " + answer);
} else {
display("The equation you entered is invalid");
}
}

每当输入有效表达式时,控制台中都会显示以下错误:

Enter F for file calculator or K for keyboard input
k
Please enter an equation
10 2 <<
The equation you entered is invalid
Please enter an equation

我无法弄清楚我的验证的哪一部分对于这些表达式是错误的。

最佳答案

问题出在您的operators正则表达式上。用户更像是:

("\\+|\\-|\\*|\\/|<<|>>|\\%|\\&|\\|")

关于java - 代码验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34119672/

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