我写了一个简单的计算器,我希望计算器重新启动,直到我按下“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/