我需要编码方面的帮助。我正在用Java编程再次练习,今天我正在创建一个具有与真实计算器相同功能的计算器,但是我又遇到了错误,无法再次计算。
好吧,我希望我的计算器能够工作,而不是像这样从用户那里逐行输入:-
在代码输出中
Enter Number: 1
Enter Operator (+,-, /, *, ^ (Power) or s (Square): +
Enter Number: 2
Ans: 3
我希望它能够计算出用户按下回车键的时间,如下所示:-
我想要的输出
enter number: 1+2*4
Ans: 12
因此,他们可以在按Enter键之前添加任意数量的长数字。在计算循环中,用户应该能够在使用计算器时将数字重置为。
在代码的开头,它将要求用户输入以继续或退出计算器。然后,如果继续,它将运行计算。计算器将一直循环播放,直到用户按E退出计算器为止;如果退出,它将退出代码。
这是我出错的地方。首先,我无法弄清楚如何从循环计算器内的循环中摆脱出来,其次在用户按下E时在代码开头],它本应退出计算器,但没有退出。 t。第三个错误是当用户使用平方来计算时,我希望它直接显示答案而不是询问其他数字。
并且我想简化计算部分public static void main(String[] args)
中的代码。是否可以将switch case放入方法中并在main中调用它?或您对如何简化计算部分有何建议?
请帮助我:(
public class TestingCalculator {
public static void main(String[] args){
double answer = 0;
double numA, numB;
char operator;
char activateCalc;
boolean calculator = false;
System.out.println("Welcome to the Calculator.");
System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");
Scanner ans = new Scanner(System.in);
String a = ans.next();
activateCalc = a.charAt(0);
while (activateCalc != 'E' || activateCalc != 'e') {
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
String n =input.next();
numA = Double.parseDouble(n);
while (calculator = true) {
//User enter their operator.
System.out.print("Enter Operator (+,-, /, *, ^ (Power) or s (Square): ");
operator = input.next().charAt(0);
System.out.print("Enter number: "); //User enter the continues number
numB = input.nextDouble();
switch (operator) {
case '=':
System.out.print(answer);
break;
case '+':
answer = add(numA,numB);
break;
case '-':
answer =subtract(numA,numB);
break;
case '*':
answer = multiply(numA,numB);
break;
case '/':
answer = divide(numA,numB);
break;
case '^':
answer = power(numA, numB);
break;
case 's':
case 'S':
answer = Math.pow(numA, 2);
break;
}
//The calculation answer of the user input
System.out.println("Answer: " + answer);
numA = answer;
// to exit calculator.
System.out.println("Press E to Exit the calculator: ");
if (activateCalc = 'E' || activateCalc = 'e') {
break;
}
}
}
ans.close();
}
//Method for the operators.
static double add(double numA, double numB) {
double answer = numA + numB;
return answer;
}
static double subtract(double numA, double numB) {
double answer = numA - numB;
return answer;
}
static double multiply(double numA, double numB) {
double answer = numA * numB;
return answer;
}
static double divide(double numA, double numB) {
double answer = numA / numB;
return answer;
}
static double power(double numA, double numB) {
int answer = (int) Math.pow(numA, numB);
return answer;
}
static double Square(double numA, double numB) {
int answer = (int) Math.pow(numA, 2);
return answer;
}
}
我需要编码方面的帮助。我正在用Java编程再次进行练习,今天我正在创建一个具有与真实计算器相同功能的计算器,但是我又遇到了错误,无法使用...
此问题需要调试详细信息,因此我们开始:
尝试下面的代码和一个建议也尝试处理负面情况。