我不久前开始学习Java,我认为制作一个可以在终端中运行的计算器.最近我添加了一个数组列表来存储历史记录,然后出了点问题.计算器程序:
import java.util.Scanner;
import java.util.ArrayList;
public class calc_case {
public static void main(String[] args) {
System.out.println("Welcom to The Calculator!");
double a;
double b;
double c;
Scanner input0;
int input = 0;
ArrayList<Double> history = new ArrayList<Double>();
while (input != 6) {
try {Thread.sleep(2000);} catch(InterruptedException ex) {Thread.currentThread().interrupt();}
a = 0; b = 0; c = 0; input = 0;
System.out.println("#################################################");
System.out.println("How can I help you?");
System.out.println("1-Add\n2-Subtrackt\n3-Devide\n4-Multiply\n5-Show history\n6-Exit");
input0 = new Scanner(System.in);
input = input0.nextInt();
switch (input) {
case 1: //add
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a + b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 2: //subtrackt
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a - b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 3: //devide
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a/b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 4: //multiply
System.out.println("Input two numbers:");
input0 = new Scanner(System.in);
a = input0.nextDouble();
input0 = new Scanner(System.in);
b = input0.nextDouble();
c = a*b;
System.out.println("Calculating... \nThe answer is: " + c );
break;
case 5: //history
for (int x = 0; x < history.size(); x++) {
System.out.println(history.get(x));
}
case 6: //exit
System.out.println("Goodbye!\n Killing process... " + " OK");
default:
history.add(c);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
将案例5添加为"显示历史记录"并将案例5"退出"移至案例6"退出"后选择选项5("显示历史记录")后,我得到:
Goodbye!
Killing process... OK
Run Code Online (Sandbox Code Playgroud)
我尝试重新编译程序,删除类文件,并将程序粘贴到新文件.我的计划有什么问题?
两件事情:
case 5; 所以你总是陷入下一个案例.下一个也是如此case 6.从"清晰编码"的角度来看:阅读"单层抽象"原则.你真的不希望在一个方法中有这么多代码; 例如:你的每个案例块......应该进入自己的方法.您想要创建可以一目了然的小"单位".超过10行或更多的东西总是需要比更小的东西更多的工作!
而且你知道; 当每个代码都这样:...
case 3:
divide();
break;
case 4:
multiply();
break;
Run Code Online (Sandbox Code Playgroud)
你不觉得自己会发现自己的问题吗?!