简单的Java控制台计算器 - 清洁代码

时间:2017-07-31 17:40:14

标签: java calculator

我是Java编程的新手,但从一开始我就想编写干净的代码。我准备了简单的控制台计算器,但想要做得更好。有什么可以改变以使代码更清晰?你如何建议添加try / catch块和异常?

主要课程:

import Calculator.Calculator;

public class App {

public static void main(String[] args) {
    Calculator calculator= new Calculator();
    calculator.action();
  }
}

和Calculator类:     包计算器;

import java.util.Scanner;

public class Calculator {
private int number1;
private int number2;
private int userActionChoice;

public void action() {
    displayMenu();
    getUserAction();
    getNumbers(number1, number2);
    executeUserAction(userActionChoice);
}

private void displayMenu() {
    System.out.println("Welcome to my calculator!\n");
    System.out.println("Please choose action: ");
    System.out.println("1. Add");
    System.out.println("2. Subtract");
    System.out.println("3. Multipy");
    System.out.println("4. Divide");
}

private int getUserAction() {
    Scanner gettingUserAction = new Scanner(System.in);
    userActionChoice = gettingUserAction.nextInt();
    return userActionChoice;
}

public void getNumbers(int num1, int num2) {
    System.out.println("Please enter first number: ");
    getNum1(num1);
    System.out.println("Please enter second number: ");
    getNum2(num2);
}

private void getNum1(int number1) {
    Scanner gettingNum1 = new Scanner(System.in);
    this.number1 = gettingNum1.nextInt();
}

private void getNum2(int number2) {
    Scanner gettingNum2 = new Scanner(System.in);
    this.number2 = gettingNum2.nextInt();
}

private void executeUserAction(int choice) {
    switch (choice) {
    case 1: {
        System.out.println(add());
        break;
    }
    case 2: {
        System.out.println(subtract());
        break;
    }
    case 3: {
        System.out.println(multiply());
        break;
    }
    case 4: {
        System.out.println(divide());
        break;
    }
    default: {
        System.out.println("Unknown command!");
    }
    }
}

private int add() {
    return number1 + number2;
}

private int subtract() {
    return number1 - number2;
}

private int multiply() {
    return number1 * number2;
}

private int divide() {
    if(number2 != 0) {
    return number1 / number2;
    }
    else {
        System.out.println("Cannot divide by 0!");
        return 0;
    }
}
}

感谢您的任何建议!

0 个答案:

没有答案