问题描述
我当前正在尝试显示一个实心的星号正方形和一个空心的星号:
I'm currently trying to display a filled asterisk square and a hollow asterisk :
********** **********
********** * *
********** * *
********** * *
********** **********
相反,我得到以下输出:
Instead, I'm getting this output:
**********
**********
**********
**********
**********
**********
* *
* *
* *
**********
我不太确定如何使其并排而不是上下移动.我是否必须将空心嵌套循环放入填充循环内,还是必须做其他事情?这是我的代码:
I'm not so sure how to make it side by side instead of up and down. Do I have to put the hollow nested loop inside the filled loop or do I have to do something else? Here is my code:
public class doubleNestedLoops {
public static void main(String[] args) {
//Filled Square
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
System.out.print("*");
}
System.out.println();
}
//Hollow Square
for (int j = 1; j <= 5; j++) {
for (int i = 1; i <= 10; i++) {
if (j == 1 || j == 5 || i == 1 || i == 10) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
推荐答案
John Martinez的回答很好,但是效率低下.我将逐步将您的代码放在下面,并对其进行了修改:
John Martinez' answer works fine, but it's a little inefficient. I'll put a step by step below your code, which I revamped:
public class Main {
public static void main(String[] args) {
//Both Squares
StringBuilder filledLine = new StringBuilder(10);
StringBuilder hollowLine = new StringBuilder(10);
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
filledLine.append("*");
if (i == 1 || i == 5 || j == 1 || j == 10) {
hollowLine.append("*");
} else {
hollowLine.append(" ");
}
}
System.out.println(filledLine + " " + hollowLine);
filledLine.delete(0, filledLine.length());
hollowLine.delete(0, hollowLine.length());
}
}
}
第1步:将您的两个循环转换为一个循环.这是因为一旦创建新行,便无法在同一行上打印.
Step 1: Convert your two loops to one loop. This is because you cannot print on the same line once you've made a new line.
Step2:因为我们将在循环中使用字符串,所以使用 StringBuffer
效率更高,因此我们不会不断创建新的字符串
Step2: Because we'll be using Strings in a loop, it's more efficient to use a StringBuffer
, so we don't constantly make new strings
第3步:将逻辑的所有输出写入缓冲区,而不是控制台.
Step 3: Write all of the output from your logic to the buffers instead of the console.
第4步:在填充缓冲区时,一次只打印一行.
Step 4: Print the buffers one line at a time, as we fill them.
第5步:获利!
这篇关于并排显示实心和空心的星号正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!