Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

정사각형 별 패턴을 인쇄하는 Java 프로그램

<시간/>

이 기사에서는 정사각형 별 패턴을 인쇄하는 방법을 이해합니다. 패턴은 여러 for 루프와 인쇄 문을 사용하여 형성됩니다.

아래는 동일한 데모입니다 -

입력

입력이 -

라고 가정합니다.
Enter the length of a side : 8

출력

원하는 출력은 -

The square pattern :
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

알고리즘

Step 1 - START
Step 2 - Declare three integer values namely i, j and my_input
Step 3 - Read the required values from the user/ define the values
Step 4 - We iterate through two nested 'for' loops to get space between the characters.
Step 5 - After iterating through the innermost loop, we iterate through another 'for' loop. This will help print the required character.
Step 6 - Now, print a newline to get the specific number of characters in the subsequent lines.
Step 7 - Display the result
Step 8 - Stop

예시 1

여기에서 입력은 8a 프롬프트를 기반으로 사용자가 입력하고 있습니다. 코딩 그라운드 도구에서 이 예제를 라이브로 사용해 볼 수 있습니다. 정사각형 별 패턴을 인쇄하는 Java 프로그램 .

import java.util.Scanner;
public class SquarePattern{
   public static void main(String args[]){
      int i, j, my_input;
      System.out.println("Required packages have been imported");
      Scanner my_scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter the length of a side : ");
      my_input = my_scanner.nextInt();
      System.out.println("The square pattern : ");
      for(i = 1; i <= my_input; i++){
         for(j = 1; j <= my_input; j++){
            System.out.print("*");
         }
         System.out.print("\n");
      }
   }
}

출력

Required packages have been imported
A reader object has been defined
Enter the length of a side : 8
The square pattern :
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *

예시 2

여기서 정수는 이전에 정의되었으며 그 값은 콘솔에 액세스되어 표시됩니다.

public class SquarePattern{
   public static void main(String args[]){
      int i, j, my_input;
      my_input = 8;
      System.out.println("The length of a side is defined as " +my_input);
      System.out.println("The square pattern : ");
      for(i = 1; i <= my_input; i++){
         for(j = 1; j <= my_input; j++){
            System.out.print("* ");
         }
         System.out.print("\n");
      }
   }
}

출력

The length of a side is defined as 8
The square pattern :
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * *