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

如何编写getName静态方法,实现在main类中打印指定字符串数组内容?

How to Implement the getName Method to Print Your String Array

Hey there! Let's fix this up step by step. First, I noticed a tiny typo in your original array: "Olson, Ashely," + "Perez, Julisa" is accidentally combining two names into one string (plus a misspelling of "Ashley"). I'll correct that in the examples below so everything works as expected.

Your goal is to write the getName method so that calling it from main outputs all the names in the array. Here are two practical approaches that fit your method signature:

Approach 1: Return a formatted string with each name on a new line

This method builds a single string containing every name (each on its own line) that you can print directly in main:

public class NamePrinter {
    // Corrected array with fixed typo and split names
    static String[] name = {"Alberts, Nancy", "Bly, Joshua", "Cox, Alex", "Hood, Ben", "Kelly, Amber", "Lizarde, Adriana", "Olson, Ashley", "Perez, Julisa", "Perez, Maria", "Rhodes, Jonathan"};

    public static String getName(String[] array) {
        // Use StringBuilder for efficient string concatenation (better than + in loops)
        StringBuilder nameBuilder = new StringBuilder();
        for (String person : array) {
            nameBuilder.append(person).append("\n"); // Add each name followed by a newline
        }
        // Trim removes the extra newline at the end
        return nameBuilder.toString().trim();
    }

    public static void main(String[] args) {
        // Get the formatted string and print it
        String allNames = getName(name);
        System.out.println(allNames);
    }
}

Approach 2: Return a comma-separated string of names

If you prefer all names in a single line separated by commas, use Java's built-in String.join method for a cleaner, more concise implementation:

public class NamePrinter {
    static String[] name = {"Alberts, Nancy", "Bly, Joshua", "Cox, Alex", "Hood, Ben", "Kelly, Amber", "Lizarde, Adriana", "Olson, Ashley", "Perez, Julisa", "Perez, Maria", "Rhodes, Jonathan"};

    public static String getName(String[] array) {
        // Join all array elements with ", " as the separator
        return String.join(", ", array);
    }

    public static void main(String[] args) {
        System.out.println(getName(name));
    }
}

Quick notes on why these work:

  • Approach 1 is ideal for readability when you want each name on its own line. StringBuilder avoids the performance overhead of repeated string concatenation with + in loops.
  • Approach 2 leverages a built-in Java method to handle the joining logic, making the code short and easy to maintain for simple comma-separated output.

内容的提问来源于stack exchange,提问作者Help

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:28:09