我试图使number2的值仅用于循环的第一次迭代。我唯一能弄清楚的方法是如何使number2的值为整个方程的数字。例:如果我把3 +3+3=,则方程是6,因为number2一直被设置为数字,而数字被设置为3。
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
// Identifiers
int i = 1; // This int is what makes a ">" be printed on every new line.
final String end = "=";
double number;
String input;
String input2;
int yes;
int index;
int length;
double math = 0;
double number2;
// Prompt for the user on how to input the numeric expression.
System.out.println("Enter your numeric expression in the following form:");
System.out.println("number operator number operator number =");
System.out.println("Leave a blank space after each number or operator.");
System.out.println("Example: 3.5 * 3 - 5 / 2.5 =" + '\n');
input = "0";
while (!input.equals(end)) {
input = scnr.next();
number = Double.parseDouble(input);
number2 = number;
// System.out.println("num2 is: " + number2);
System.out.println("input is: " + input);
System.out.println("number is: " + number);
input = scnr.next();
switch(input) {
case "+":
math = number2 + number; System.out.println("add" + math);
break;
case "-":
math = number2 - number; System.out.println("sub" + math);
break;
case "*":
math = number2 * number; System.out.println("mult" + math);
break;
case "/":
math = number2 / number; System.out.println("div" + math);
}
number2 = math;
// System.out.println("num2 is: " + number2);
}
System.out.println("Answer: " + math);
/* double hiu = 3 / 2 * 3 - 2 + 1 ;
System.out.println("yes " + hiu); */
}
}发布于 2022-03-21 03:58:55
最简单的解决方案是将解析第一个数字的代码移出循环。你想让它发生一次,而不是绕过去。有点像
String input = scanner.next();
double number = Double.parseDouble(input);
double number2;
while(!input.equals(end)) {
input = scanner.next();
switch(input) {
case "+":
input = scanner.next();
number2 = Double.parseDouble(input);
number = number + number2;
break;
case "-":
...
}
}发布于 2022-03-22 01:16:45
这两种方法都是解决办法。您还可以使用do循环,应用Sorifiend的答案的逻辑。决定因素将是计算复杂度与代码可读性与模块化之间的权衡。
计算复杂性:如果您正在进行很多计算,并且在设置变量之前不需要评估条件是否满足,那么将其从您的循环中删除。
代码可读性:使用注释来建立将该过程从循环中提取出来的逻辑。在解析字符串时,需要在循环之外声明一个变量来更新/存储您的答案。在解析任何内容之前,可以将此变量定义为0.0,因为这是一个对计算没有影响的中性值。
模块化:您不希望外部变量意外孤立。这并不特别适用于您的用例。当你在旅途中前进的时候,要记住一个概念。
https://stackoverflow.com/questions/71552571
复制相似问题