gpt4 book ai didi

java - 我希望计算器重新启动,直到我按下 'q' 字母

转载 作者:行者123 更新时间:2023-12-01 23:31:22 25 4
gpt4 key购买 nike

我写了一个简单的计算器,我希望计算器重新启动,直到我按下“q”按钮。问题是我无法让它做到这一点。

我尝试了一些 do/while 循环,但我不断收到错误。

import java.util.Scanner;

public class Assignment2_3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("Welcome to my mini calculator program!");
System.out.println("Please enter the numbers along operation (press q to exit):");
int number1 = in.nextInt();
char typeoftheoperation = in.next().charAt(0);
int number2 = in.nextInt();
String terminate = "";
double result;
switch (typeoftheoperation) {
case ('+'):
result = number1 + number2;
System.out.println("The result is :" + result);
break;

case '-':
result = number1 - number2;
System.out.println("The result is :" + result);
break;

case '*':
result = number1 * number2;
System.out.println("The result is :" + result);
break;

case '/':
result = number1 / number2;
System.out.println("The result is :" + result);
break;
terminate = in.next();
if (terminate.equals("q"))
in.close();
}



}
}
}

我希望计算器继续运行,直到我决定输入“q”,然后它应该停止。

最佳答案

这是针对您所问问题的临时解决方案。您可能还想使用 try...catch... 来解决“inputmismatchException”。但这暂时有效。

    import java.util.Scanner;

public class Assignment2_3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(true) {
System.out.println("Welcome to my mini calculator program!");
System.out.println("Please enter the numbers along operation (press q to exit):");
int number1 = in.nextInt();
char typeoftheoperation = in.next().charAt(0);
int number2 = in.nextInt();
String terminate = "";
double result;
switch (typeoftheoperation) {
case ('+'):
result = number1 + number2;
System.out.println("The result is :" + result);
break;

case '-':
result = number1 - number2;
System.out.println("The result is :" + result);
break;

case '*':
result = number1 * number2;
System.out.println("The result is :" + result);
break;

case '/':
result = number1 / number2;
System.out.println("The result is :" + result);
break;
}
terminate = in.next();
if (terminate.equals("q")) {
in.close();
System.out.println("You turned off the calculator! See you again");
break;
}



}
}
}

关于java - 我希望计算器重新启动,直到我按下 'q' 字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58289127/

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