Skip to main content
Code Review

Return to Answer

Commonmark migration
Source Link

###Revised code

Revised code

###Revised code

Revised code

Source Link
Phrancis
  • 20.5k
  • 6
  • 69
  • 155

###Revised code

For reference, I am posting the revised code showing the improvements I made, all thanks to the reviews!

Here is what I applied (thank you @Legato, @Heslachler, @Rhuarc13!)

  • Used better naming and formatting of class, method and variable names

  • Used better output formatting using System.out.printf()

  • Added non-zero check

  • Added getters and called those from main instead of local variables

Calculator.java

public class Calculator {
 private final double NUM_1;
 private final double NUM_2;
 Calculator(double num1, double num2) {
 this.NUM_1 = num1;
 this.NUM_2 = num2;
 }
 // Getters
 public double getNum1() {
 return this.NUM_1;
 }
 public double getNum2() {
 return this.NUM_2;
 }
 // Calculation methods
 public double add() {
 return NUM_1 + NUM_2;
 }
 public double subtract() {
 return NUM_1 - NUM_2;
 }
 public double multiply() {
 return NUM_1 * NUM_2;
 }
 public double divide() {
 return NUM_1 / NUM_2;
 }
 public double exponent() {
 return Math.pow(NUM_1, NUM_2);
 }
}

TestCalculator.java

class TestCalculator {
 public static void main(String[] args) {
 double num1 = 3.74;
 double num2 = 6.51482;
 if (num1 == 0 || num2 == 0) {
 System.out.println("Error: Please enter only non-zero values");
 } else {
 Calculator calc = new Calculator(num1, num2);
 // show outputs from calculations
 System.out.printf("Number 1: %.4f\n", calc.getNum1());
 System.out.printf("Number 2: %.4f\n", calc.getNum2());
 System.out.printf("Addition: %.4f\n", calc.add());
 System.out.printf("Subtraction: %.4f\n", calc.subtract());
 System.out.printf("Multiplication: %.4f\n", calc.multiply());
 System.out.printf("Division: %.4f\n", calc.divide());
 System.out.printf("Exponent: %.4f\n", calc.exponent());
 }
 }
}

New output formatting:

Number 1: 3.7400
Number 2: 6.5148
Addition: 10.2548
Subtraction: -2.7748
Multiplication: 24.3654
Division: 0.5741
Exponent: 5397.0367

Post Made Community Wiki by Phrancis
lang-java

AltStyle によって変換されたページ (->オリジナル) /