计算器应用程序不工作-Java
我正在做一个基于文本的计算器,可以做加法、减法、除法、乘法和幂运算。到目前为止,我编写的代码似乎可以工作,但当它到达确定输入的文本是+、-、/、*、还是^的部分时,它会无休止地循环,无法识别输入计算器应用程序不工作-Java,java,math,calculator,Java,Math,Calculator,我正在做一个基于文本的计算器,可以做加法、减法、除法、乘法和幂运算。到目前为止,我编写的代码似乎可以工作,但当它到达确定输入的文本是+、-、/、*、还是^的部分时,它会无休止地循环,无法识别输入 double inputX; // Used for input 2 double inputY; // Used for input 1 double output; // Used for math purposes String inputS; // Us
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!");
解决方案很可能是显而易见的,但我不是您永远不会将
corrInput
值更改为false
,因此它永远不会退出嵌套的while
corrInput = false;
您可能还希望使用
str1.equals(str2)
来比较字符串,而不是=
如果我更改corrInput=false,它将绕过整个数学运算您可能希望在时使用If
而不是。想想你希望你的程序如何运作。