猿问

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

我在 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( );

    }

  }

}


一只萌萌小番薯
浏览 215回答 3
3回答

繁花如伊

qsdSystem.out.println()代码中的语句将始终打印一行。也许删除它们可以解决您的问题。sdSystem.out.println()代码中的语句将始终打印一行。也许删除它们可以解决您的问题。sdSystem.out.println()代码中的语句将始终打印一行。也许删除它们可以解决您的问题。System.out.println()代码中的语句将始终打印一行。也许删除它们可以解决您的问题。System.out.println()代码中的语句将始终打印一行。也许删除它们可以解决您的问题。sssssssssssssssssssssssssssssssssssssssssssssssssssssssssSystem.out.println()代码中的语句将始终打印一行。也许删除它们可以解决您的问题。System.out.println()代码中的语句将始终打印一行。也许删除它们可以解决您的问题。

胡说叔叔

System.out.println() 将移动到下一行,移动后不能回到上一行。您必须更改整个逻辑才能获得所需的模式&nbsp; &nbsp; int n= 5;&nbsp; &nbsp; for ( int i = 0; i <n; i++) {&nbsp; &nbsp; &nbsp; &nbsp; for ( int j = 0; j <n; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 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) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("* ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("&nbsp; ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j < n; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(i==0||j==0||j==n-1||i==n/2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("* ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("&nbsp; ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }输出:* * * * * * * * * *&nbsp;*&nbsp; &nbsp; &nbsp; &nbsp;* *&nbsp; &nbsp; &nbsp; &nbsp;*&nbsp;* * * * * * * * * *&nbsp;*&nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp;*&nbsp;*&nbsp; &nbsp; &nbsp; &nbsp;* *&nbsp; &nbsp; &nbsp; &nbsp;*&nbsp;

小怪兽爱吃肉

System.out.print()将输出立即一个接一个地放置,它们之间没有换行符。这就是为什么某些部分出现在同一行中的原因。如果您希望它垂直打印,请使用System.out.println(),这将使下一行打印到下一行。
随时随地看视频慕课网APP

相关分类

Python
我要回答