gpt4 book ai didi

java - 简单的计算器操作

转载 作者:搜寻专家 更新时间:2023-11-01 03:05:57 25 4
gpt4 key购买 nike

我试图简化计算器程序的长代码,但我遇到了障碍。我为每个计算器运算符都有一个新的 else if 语句,但我想做的是允许用户在一行中手动输入他们想要执行的整个操作,并让代码计算它。

这是我所拥有的:

do {
System.out.println("What function would you like to perform?");
System.out.print("Exit Calculator (Q), Add (+), Subtract (-), Multiply (x), Divide (/): ");
maininput = in.next();

if (maininput.equals("+")) {
System.out.print("Enter the first number to add: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to add: ");
num2 = in.nextDouble();
System.out.println();

answer = num1 + num2;

System.out.println(num1 + " + " + num2 + " = " + answer);
System.out.println();
}
else if (maininput.equals("-")) {
System.out.print("Enter the first number to subtract: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to subtract: ");
num2 = in.nextDouble();
System.out.println();

answer = num1 - num2;

System.out.println(num1 + " - " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("x")) {
System.out.print("Enter the first number to multiply: ");
num1 = in.nextDouble();
System.out.print("Enter the second number to multiply: ");
num2 = in.nextDouble();
System.out.println();

answer = num1 * num2;

System.out.println(num1 + " x " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("/")) {
System.out.print("Enter the first number to divide: ");
num1 = in.nextDouble();
do {
System.out.print("Enter the second number to divide: ");
num2 = in.nextDouble();
System.out.println();
if (num2 == 0) {
System.out.println("Cannot divide by 0! Please enter a different number.");
}
} while (num2 == 0);

answer = num1 / num2;

System.out.println(num1 + " / " + num2 + " = " + answer);
System.out.println();
}
else if(maininput.equals("Q") || maininput.equals("q") || maininput.equals("EXIT") || maininput.equals("exit")) {
in.close();
System.exit(0);
}
else {
System.out.println(maininput + " is not a valid operand. Please try again.");
System.out.println();
}
} while (maininput != "Q" && maininput != "q");

这就是我想要的输出:

Enter operation:
4 * 6
4 * 6 = 24

应该可以在这里一行输入任何操作。我不是要你为我写计算器,我是要问如何让计算机离线读取整个操作并计算它,然后打印出来。

最佳答案

如果你使用 scanner readLine 那么你可以读取整行

例如

 4 * 6

然后可以拆分这条线以获得三个标记

 String tokens [] = line.split (" ");

然后就可以看到根据token[1]做了什么操作

 if (token[1].equals ("-") {

//lets minus token[2] from token[0]
// need to convert String to Number
}

关于java - 简单的计算器操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22339324/

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