我正在制作一个基于文本的计算器,可以进行加法,减法,除法,乘法和幂。到目前为止我编写的代码似乎有效,但是当它到达确定输入文本是+, - ,/,*还是^的部分时,它会无限循环并且无法识别输入。
double inputX; // Used for input 2
double inputY; // Used for input 1
double output; // Used for math purposes
String inputS; // Used for string input
String subt; // Store the - in a string
subt = "-";
boolean corrInput = true;
boolean repeat = true;
while (repeat == true){
System.out.print("Please enter a number: ");
inputX = TextIO.getlnDouble(); // Retrieves inputX
System.out.println("x: " + inputX + "\n");
System.out.print("Please enter a number: ");
inputY = TextIO.getlnDouble(); // Retrieves inputY
System.out.println("y: " + inputY + "\n");
while (corrInput == true){
System.out.println("Choose an operation: +, -, *, /, ^.");
inputS = TextIO.getlnString(); // Retrieves a strings input
// Calculator logic
if (inputS == subt){
output = inputX - inputY; // X minus Y
System.out.println("Calculatorator says that " + inputX + " - " + inputY
+ " = " + output);
}
else if (inputS == "+"){
output = inputX - inputY; // X plus Y
System.out.println("Calculatorator says that " + inputX + " + " + inputY
+ " = " + output);
}
else if (inputS == "*"){
output = inputX * inputY; // X multiplied by Y
System.out.println("Calculatorator says that " + inputX + " * " + inputY
+ " = " + output);
}
else if (inputS == "/"){
output = inputX / inputY; // X divided by Y
System.out.println("Calculatorator says that " + inputX + " / " + inputY
+ " = " + output);
}
else if (inputS == "^"){
output = Math.pow(inputX, inputY); // X to the power of Y
System.out.println("Calculatorator says that " + inputX + " ^ " + inputY
+ " = " + output);
}
else {
System.out.println("Please provide a valid input. '" + inputS
+ "' is not valid input");
}
}
System.out.println("Want to do another Calculatoration?");
repeat = TextIO.getBoolean(); // Retrieves input as a boolean
}
System.out.println("Thank you for using my calculator!");
解决方案很可能很明显,但我不是
答案 0 :(得分:0)
您永远不会将corrInput
值更改为false
,因此它不会永远不会退出嵌套时间。
corrInput = false;
您可能还希望使用str1.equals(str2)
来比较字符串而不是==
。