gpt4 book ai didi

java - 一个简单的控制台计算器

转载 作者:行者123 更新时间:2023-11-30 07:09:33 24 4
gpt4 key购买 nike

我设计了一个简单的控制台计算器,如下所示,但我需要创建一个可以重新运行程序的循环:

这样我就不需要一次又一次地运行该程序,它可以接受用户的输入并自行运行。

private static Scanner op;
private static Scanner input;
private static Scanner cont;

public static void main(String args[]) {
double num1;
double num2;
double ans = 0;
double l1;
double l2;
String operation;

input = new Scanner(System.in);
System.out.println("Please input your first number:");
num1= input.nextDouble();

System.out.println("Please input the second numer:");
num2= input.nextDouble();

op = new Scanner(System.in);
System.out.println("Select your operation:");
operation = op.next();

if (operation.equals("+")){
System.out.println("Your Result is :" + (num1+num2));
}
if (operation.equals("-")){
System.out.println("Your Result is:" + (num1-num2));
}
if (operation.equals("/")){
if (num2 == 0){
System.out.println("Your Input is Invalid");}
else {
System.out.println("Your result is :" + (num1/num2));
}

}
if (operation.equals("*")){
System.out.println("Your result is:" + (num1*num2));
}
if (operation.equals("%")){
System.out.println("Your result is:" + (num1*100/num2));
}
if (operation.equals("^")){
ans= Math.pow(num1, num2);
System.out.println("Your result is:"+ans);
}
if (operation.equals("log")){
l1=Math.log(num1);
l2=Math.log(num2);
System.out.println("Your result is:"+l1/l2);
}
operation = cont.next();
System.out.println("Do you wish to perform any other operation?");
if (operation.equals("Yes")){

else{
System.out.println("Thank You");
}
}
}

最佳答案

您可以创建一个函数并使用如下循环调用它:

private static void myfunction(){
//put your code here
}

public static void main(String[] args) {
//call your function until your condition is false
while(myconditionistrue){
myfunction();
}
}

如果您想询问用户是否继续使用这种方式:

private static void myfunction() {
//put your code here
}

public static void main(String[] args) {

String exit;
Scanner scan = new Scanner(System.in);
do {
//call your function or you can put all your code here
myfunction();
System.out.println("You want to continue? y : n :");
exit = scan.next();
} while (exit.equals("y"));
}

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

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