gpt4 book ai didi

java - 如何在同一水平线上显示不同的图案?

转载 作者:行者123 更新时间:2023-12-02 10:46:28 25 4
gpt4 key购买 nike

我在java中设计了不同的图案,然后我希望所有图案都打印在一条水平线上。我的程序以垂直线显示输出。这是我的代码:

package demo;

public class PatternDemo {

public static void main( String[] args ) throws InterruptedException {

int n = 5;

for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ ) {
if ( i == 0 || j == 0 || i == n / 2 || (i <= n / 2 && j == n - 1)
|| i == n - 2 && j == n - 3 || i == n - 1 && j == n - 1 ) {
System.out.print( "* " );
} else {
System.out.print( " " );
}

}
System.out.println( );

}

for ( int i = 0; i < n; i++ ) {
for ( int j = 0; j < n; j++ ) {

if ( i == 0 || j == 0 || j == n - 1 || i == n / 2 ) {
System.out.print( "* " );
} else {
System.out.print( " " );
}
}
System.out.println( );
}
}
}

最佳答案

System.out.println() 将移动到下一行,移动后您无法返回到上一行。您必须更改整个逻辑才能获得所需的模式

    int n= 5;
for ( int i = 0; i <n; i++) {
for ( int j = 0; j <n; j++) {
if(i==0||j==0||i==n/2||(i<=n/2&&j==n-1)||i==n-2&&j==n-3||i==n-1&&j==n-1) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
for (int j = 0; j < n; j++) {

if(i==0||j==0||j==n-1||i==n/2){
System.out.print("* ");
}else {
System.out.print(" ");
}

}
System.out.println();
}

输出:

* * * * * * * * * * 
* * * *
* * * * * * * * * *
* * * *
* * * *

关于java - 如何在同一水平线上显示不同的图案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52523534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com