【问题标题】:returning a string from the string array lengths equal to the input integer从字符串数组中返回一个字符串,长度等于输入整数
【发布时间】:2026-01-10 22:20:03
【问题描述】:

我正在尝试通过从eleloosp 数组到j 元素构建一个句子来创建一个返回字符串的方法。所以如果j = 3 那么输出将是" How about a nice "
我不想通过执行if(j == 3) 之类的操作来硬编码 if 语句,然后输出这个特定的东西。

我将如何做到这一点,以便我可以获取输入整数而不是硬编码 if 语句。

public class TestForEachLoop
{
    private String[] eleloosp = {"How", "about", "a", "nice","tea"};

    public String getCF(int j){
        for(int i = 0; i < eleloosp.length; i++){
            if( j == eleloosp.length){
                System.out.println();
            }
        }
    }
}

【问题讨论】:

  • 为什么值为 3 会给出一个包含 四个 元素的返回字符串?您是否尝试过使用StringJoiner?这与数组长度有什么关系?恐怕你的问题目前还不清楚。
  • 我试图做的是创建一个返回字符串的方法,该字符串将包含一个由 eleloosp 数组到 j 个元素组成的句子。我知道我必须使用 if 语句,但是如何从 j 中获取输入的数字并使其等于 eleloosp 数组,而无需对 if 语句中的数字进行硬编码。

标签: java arrays string loops if-statement


【解决方案1】:

您可以使用以下代码简单地做到这一点:

public class Main {
    static String[] eleloosp = { "How", "about", "a", "nice", "tea" };

    public static void main(String[] args) {
        System.out.println(getCF(2));
        System.out.println(getCF(3));
    }

    public static String getCF(int j) {
        String sentence = "";
        assert(j < eleloosp.length);

        for(int i = 0; i < j; i++){
           sentence += eleloosp[i] + " ";
        }

        return sentence;
    }
}

输出:

How about
How about a

如果您对此有帮助,请告诉我!

【讨论】:

    【解决方案2】:

    有很多方法可以做到这一点。使用以下函数的简洁方法:

    1. String#join
    2. Arrays#copyOfRange
    3. Integer#min

    演示:

    import java.util.Arrays;
    
    public class Main {
        static String[] eleloosp = { "How", "about", "a", "nice", "tea" };
    
        public static void main(String[] args) {
            // Test
            System.out.println(getCF(3));
            System.out.println(getCF(2));
            System.out.println(getCF(8));
        }
    
        public static String getCF(int j) {
            return String.join(" ", Arrays.copyOfRange(eleloosp, 0, Integer.min(j + 1, eleloosp.length)));
        }
    }
    

    输出:

    How about a nice
    How about a
    How about a nice tea
    

    【讨论】: