gpt4 book ai didi

java - 我制作了一个 CLI 计算器,我想知道,如何让程序无限期地接受数字,直到用户输入停止命令?

转载 作者:行者123 更新时间:2023-12-02 12:25:38 25 4
gpt4 key购买 nike

你可能知道我是一个初学者,而且我知道社区并不真正喜欢我们。我不久前制作了一个多功能计算器,现在我想扩展它。在这个问题中,我将只关注一类。

import java.util.Scanner;

public class Calculator {

public static void calcMenu(Scanner input){
Scanner oper = new Scanner(System.in);
System.out.println("Please input the First number:");
double anum = input.nextDouble();

System.out.println("Please input on of the following operations:");
System.out.println("+");
System.out.println("-");
System.out.println("*");
System.out.println("/");
String equ = oper.nextLine();

System.out.println("Please input the Second number:");
double bnum = input.nextDouble();

switch (equ){
case "+":
System.out.println(anum + bnum);
break;

case "-":
System.out.println(anum - bnum);
break;

case "*":
System.out.println(anum * bnum);
break;

case "/":
System.out.println(anum / bnum);
break;
}
}
}

在这个 Java 类中,程序只能用两个数字解方程。我想让它像标准计算器一样,您可以在其中输入任意数量的数字。我想这样做,直到用户输入类似“完成”的内容并且应用程序将返回主菜单。这可能是一个非常菜鸟的问题,但请帮忙。如果您想查看整个应用程序:这里是 link

最佳答案

这会对你有所帮助! :)

import java.util.InputMismatchException;
import java.util.Scanner;

public class Calculator {

private static double answer;
private static boolean done = false;
private static Scanner in = new Scanner(System.in);

public static void main(String[] args) {

try {
new Calculator().calcExpression();
} catch (InputMismatchException e) {
System.out.println("An error occurred. ");
}
}

private void calcExpression() throws InputMismatchException {

System.out.println("Enter Your Expression Here:");

System.out.print("Num: ");
double firstNum = in.nextDouble();
in.nextLine();

while (!done) {

System.out.print("Operator: ");
String operand = in.nextLine();

if (operand.equals("=")) {
break;
}

System.out.print("Num: ");
double secondNum = in.nextDouble();
in.nextLine();

calculate(firstNum, operand, secondNum);
firstNum = answer;
}

System.out.printf("Answer is %.2f", answer);
}

private void calculate(double num1, String equ, double num2) {

switch (equ)

{
case "/":
answer = (num1 / num2);
break;

case "*":
answer = (num1 * num2);
break;

case "+":
answer = (num1 + num2);
break;

case "-":
answer = (num1 - num2);
break;

case "=":
done = true;
break;
}
}
}

关于java - 我制作了一个 CLI 计算器,我想知道,如何让程序无限期地接受数字,直到用户输入停止命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45494101/

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