返回一个带有一个字符的字符串,一个接一个地使用的字符使用循环java
您如何=)
我有任务返回字符串“@”#“一个接一个的字符串长度为5时,使用循环。
我有一个想法将“@”分配给奇数数字,#“偶数数字。
其中“@”是0,“#” is 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));
}
How are you =)
I have task to return string with characters "@" "#" one after another with string length of 5 using While loop.
I have an idea to assign "@" to odd numbers, "#" to even numbers.
Where "@" is 0, "#" is 1, "@" is 2, and so on until the end of the length of the line.
Unfortunately, I can't find information how I can do this.
Please check the following code, I hope it will be more clear what I am talking about.
I will be glad for any hint or advice, thank you :)
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));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我们在这里已经指出了两个问题,这两个问题已经在您的问题下面的评论中指出。
您在问题中定义您的任务是返回最终字符串,而不是直接打印。对于此类内容,您可以使用
StringBuiler
(请参阅下面的示例),或者简单地以任何其他方式加在一起(例如“ a” +“ b” - &gt;“ ab”
)第二个问题是迭代本身。您使用mod 2来确定您测试的值是否为偶数。这部分是正确的。但是,您总是在比较所需的长度
长度%2 == 0
而不是当前位置i
要打印。因此,您只会永远打印@
或#
长度
- 时间取决于所需的长度均匀(导致@)或奇数(导致
#
)。在下面,您可以找到有关如何正确解决任务的示例。只需在子句中与
i
中的子句在中交换<代码>
,然后将结果置换并返回。First of all we've two address two issues here as some have already pointed out in the comments beneath your questions.
You define in your question that your task is to return the final string instead of printing it directly. For such things you can either use a
StringBuiler
(see my example below) or simply concatenate in any other way ( e.g."A" + "B" -> "AB"
)The second issue is the iteration itself. You use mod 2 to determine if the value you test is even or not. This part is correct. However you're always comparing the desired length
length % 2 == 0
instead of the current positioni
of the character to print. Therefore you'll only ever print@
or#
length
-times depending on the desired length being even (leading to@
) or odd (leading to#
).Below you can find my example on how to properly solve your task. Simply exchange
length
within theif
clause withi
and concatenate the result and return it.