Return 一个使用 while 循环一个接一个地出现的字符的字符串 Java

Return a string with characters that come one after the other using while loop Java

你好吗 =)

我有任务 return 使用 While 循环一个接一个地包含字符“@”“#”的字符串,字符串长度为 5。

我有一个想法,将“@”分配给奇数,将“#”分配给偶数。

其中“@”为0,“#”为1,“@”为2,依此类推,直到该行长度结束。 不幸的是,我找不到有关如何执行此操作的信息。

请检查下面的代码,希望它能更清楚我在说什么。

如果有任何提示或建议,我将很高兴,谢谢 :)

public String drawLine(int length) {
    int i = 0;
    
        while (i < length) {
        
            //I know that the following code will take only the int length, it's just an idea
            if(length % 2 == 0) {
                i++;
                System.out.print("@");
            }
            else {
                i++;
                System.out.print("#");
            }
        }
        
    return new String("");
}

public static void main(String[] args) {
    JustATest helper = new JustATest();

    //The result should be @#@#@
    System.out.println(helper.drawLine(5));
}

首先,我们在这里解决了两个问题,有些人已经在您的问题下方的评论中指出了这一点。

您在问题中定义您的任务是 return 最终字符串而不是直接打印它。对于此类事情,您可以使用 StringBuiler(请参阅下面的示例)或以任何其他方式简单地连接(例如 "A" + "B" -> "AB")

第二个问题是迭代本身。您使用 mod 2 来确定您测试的值是否为偶数。这部分是正确的。但是,您总是比较所需的长度 length % 2 == 0 而不是要打印的字符的当前位置 i。因此,您只会打印 @# length 次,具体取决于所需的长度是偶数(导致 @)还是奇数(导致 #).

您可以在下面找到有关如何正确解决您的任务的示例。只需将 if 子句中的 lengthi 交换并将结果与​​ return 连接起来。

 public String drawLine(int length)
{
    int i = 0;

    StringBuilder builder = new StringBuilder();
    while ( i < length )
    {
        //I know that the following code will take only the int length, it's just an idea
        if( i % 2 == 0 )
        {
            i++;
            builder.append( "@" );
        } else
        {
            i++;
            builder.append( "#" );
        }
    }
    return builder.toString();
}