You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

这段Java代码是否属于良好的编程实现?

Evaluation of Your Java Code for Good Programming Practices

First, let's call out what you’re doing right: you’ve broken the problem into separate methods (input handling, printing, average calculation), which is a great start for modular code, and you’re using a proper package structure. That said, there are several areas where we can align this with standard Java best practices to make the code more robust, readable, and maintainable.

Areas for Improvement

1. Violation of Single Responsibility Principle

  • The returnAverage method does two distinct things: calculates the average and prints a message. Methods should ideally have one clear purpose—this makes code easier to test, reuse, and debug.
  • If printNumbers returns the input array while printing it, it’s mixing a side effect (printing) with a value return. As a general rule, methods should either perform an action (like printing) or return a value, not both.

2. Static Scanner Resource Leak

  • Using a static Scanner instance without ever closing it leads to resource leaks. Additionally, static members can complicate unit testing since they’re shared across all instances of the class.

3. Missing Error Handling

  • returnAverage doesn’t check if the input array is empty. This will throw an ArithmeticException (division by zero) if no numbers are entered.

4. Readability Issues

  • The chained method call in main (System.out.println(returnAverage(printNumbers(enterNumbers())))) is hard to follow. Breaking this into separate variables makes the code flow clearer and easier to debug.
  • The comment // 10 is ambiguous—always use comments to explain why something is done, not just a random value.

5. Naming and Style

  • returnAverage could be more descriptive and concise, like calculateAverage.
  • String literals should follow consistent casing: "the average is:" should be "The average is:".

Revised Code Example

Here’s a version that addresses these issues:

package com.mohamadibrah;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Break chained calls into readable, debuggable steps
        double[] userNumbers = enterNumbers();
        printNumbers(userNumbers);
        double average = calculateAverage(userNumbers);
        System.out.printf("The average is: %.2f%n", average);
    }

    // Handles input and auto-closes the Scanner to prevent leaks
    public static double[] enterNumbers() {
        try (Scanner sc = new Scanner(System.in)) { // Try-with-resources auto-manages the Scanner
            System.out.print("How many numbers would you like to enter? ");
            int count = sc.nextInt();
            double[] numbers = new double[count];
            
            for (int i = 0; i < count; i++) {
                System.out.printf("Enter number %d: ", i + 1);
                numbers[i] = sc.nextDouble();
            }
            return numbers;
        }
    }

    // Only responsible for printing numbers to console
    public static void printNumbers(double[] array) {
        System.out.println("You entered the following numbers:");
        for (double num : array) {
            System.out.printf("%.2f ", num);
        }
        System.out.println();
    }

    // Only calculates average, with guard clauses for invalid input
    public static double calculateAverage(double[] array) {
        if (array == null || array.length == 0) {
            throw new IllegalArgumentException("Array cannot be empty or null");
        }
        double sum = 0;
        for (double num : array) {
            sum += num;
        }
        return sum / array.length;
    }
}

Key Improvements:

  • Single Responsibility: Each method has one clear job (input, printing, calculation).
  • Resource Management: Uses try-with-resources to auto-close the Scanner, eliminating leaks.
  • Error Handling: Checks for empty/null arrays in calculateAverage and throws a meaningful exception.
  • Readability: Breaks main method logic into separate steps with descriptive variable names.
  • Style: Consistent casing, formatted output with printf for clarity, and precise method names.

Conclusion

Your code has a solid foundation with modular method separation, but adjusting for single responsibility, resource management, and error handling will make it more robust, maintainable, and aligned with industry best practices.

内容的提问来源于stack exchange,提问作者M.I

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:51:11