java - 我希望我的计算器重新启动,直到我按下“q”字母
问题描述
我写了一个简单的计算器,我希望计算器重新启动,直到我按下“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;
}
}
}
}
推荐阅读
- c++ - 将推力向量输入 getrf/getri 时出现问题
- perl - 如何在使用未初始化值时使 perl 退出并显示错误代码?
- slurm - Slurm 问题:Array Job VS srun in a sbatch
- c++ - OpenGL 3.0 窗口碰撞检测
- laravel - Laravel 在不同的行中存储多个值
- go - go 映射大量键的性能不佳
- python - 带有 R 的 jupyter 笔记本无法显示特定的汉字(多字节字符)
- html - 如何在此图像中嵌入响应式可播放 youtube 视频?
- css - 带有 vuejs 的进度条
- python - 为什么这个模型的准确率和f1分数无论如何都一样?