Hello. I have reviewed your code. While the logic for calculating the average is correct, there are several issues regarding resource management, naming conventions, and robustness.
Here is the detailed code review:
1. Resource Leak (Bugs / Best Practice)
- Severity: Medium
- Description: The
Scanner object is opened but never closed. In Java, objects that wrap underlying resources (like System.in) should be closed to prevent memory leaks and resource exhaustion.
- Recommendation: Use a try-with-resources block or call
sc.close() in a finally block.
2. Lack of Input Validation (Runtime Errors)
- Severity: Medium
- Description: The code assumes the user will always enter a valid
double. If a user enters text (e.g., "abc"), the program will throw an InputMismatchException and crash.
- Recommendation: Use
sc.hasNextDouble() to check input before reading or wrap the logic in a try-catch block to handle invalid inputs gracefully.
3. Violation of Naming Conventions (Code Quality)
- Severity: Low
- Description: The method is named
Average (starting with an uppercase letter). In Java, method names should follow lowerCamelCase. Additionally, the class name Exercise_1_Question_1 uses underscores, which is generally discouraged in favor of PascalCase (e.g., AverageCalculator).
- Recommendation: Rename the method to
calculateAverage or printAverage. Rename the class to AverageCalculator.
4. Logic Separation / Single Responsibility Principle (Best Practice)
- Severity: Low
- Description: The method
Average performs two tasks: it calculates the value AND prints it. This makes the method less reusable. If you later wanted to use the average for another calculation without printing it, you couldn't use this method.
- Recommendation: The method should return the
double value, and the printing should be handled by the caller (the main method).
5. Hardcoded Divisor (Best Practice)
- Severity: Low
- Description: While using
3 is mathematically correct here, when working with floating-point math, it is best practice to use double literals (e.g., 3.0) to ensure precision is maintained throughout the operation and to avoid any accidental integer division in future modifications.
- Recommendation: Change the formula to
(a + b + c) / 3.0.
Optimized Code Example
Here is a refactored version of your code addressing the points above:
import java.util.Scanner;
import java.util.InputMismatchException;
/**
* A utility to calculate the average of three numbers.
*/
public class AverageCalculator {
/**
* Calculates the average of three double values.
* @return the average result
*/
public static double calculateAverage(double a, double b, double c) {
return (a + b + c) / 3.0;
}
public static void main(String[] args) {
// Try-with-resources ensures the Scanner is closed automatically
try (Scanner sc = new Scanner(System.in)) {
System.out.println("Enter Three Numbers: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double result = calculateAverage(a, b, c);
System.out.printf("The Average of the numbers is: %.2f%n", result);
} catch (InputMismatchException e) {
System.err.println("Error: Please enter valid numeric values.");
}
}
}
Key Changes Made:
- Try-with-resources: Added
try (Scanner sc = ...) to prevent resource leaks.
- Naming: Renamed the method to
calculateAverage (lowerCamelCase).
- Return Value: The method now returns a
double instead of printing directly.
- Error Handling: Added a
try-catch block to handle non-numeric input.
- Formatting: Used
System.out.printf to control decimal places in the output for a cleaner UI.
Hello. I have reviewed your code. While the logic for calculating the average is correct, there are several issues regarding resource management, naming conventions, and robustness.
Here is the detailed code review:
1. Resource Leak (Bugs / Best Practice)
Scannerobject is opened but never closed. In Java, objects that wrap underlying resources (likeSystem.in) should be closed to prevent memory leaks and resource exhaustion.sc.close()in afinallyblock.2. Lack of Input Validation (Runtime Errors)
double. If a user enters text (e.g., "abc"), the program will throw anInputMismatchExceptionand crash.sc.hasNextDouble()to check input before reading or wrap the logic in atry-catchblock to handle invalid inputs gracefully.3. Violation of Naming Conventions (Code Quality)
Average(starting with an uppercase letter). In Java, method names should follow lowerCamelCase. Additionally, the class nameExercise_1_Question_1uses underscores, which is generally discouraged in favor of PascalCase (e.g.,AverageCalculator).calculateAverageorprintAverage. Rename the class toAverageCalculator.4. Logic Separation / Single Responsibility Principle (Best Practice)
Averageperforms two tasks: it calculates the value AND prints it. This makes the method less reusable. If you later wanted to use the average for another calculation without printing it, you couldn't use this method.doublevalue, and the printing should be handled by the caller (themainmethod).5. Hardcoded Divisor (Best Practice)
3is mathematically correct here, when working with floating-point math, it is best practice to use double literals (e.g.,3.0) to ensure precision is maintained throughout the operation and to avoid any accidental integer division in future modifications.(a + b + c) / 3.0.Optimized Code Example
Here is a refactored version of your code addressing the points above:
Key Changes Made:
try (Scanner sc = ...)to prevent resource leaks.calculateAverage(lowerCamelCase).doubleinstead of printing directly.try-catchblock to handle non-numeric input.System.out.printfto control decimal places in the output for a cleaner UI.