vendredi 17 septembre 2021

how can make the number of rows in the butterfly same as the entry of the user?

I'm fairly new to java, and I'm facing some problems. how can I make the number of rows printed in the butterfly pattern the same as the entry of the user and I was trying to allow the user to enter only odd numbers using if statements but it didn't work for me. any help or advice will be appreciated. thanks!

import java.util.Scanner;
public class Patterns {

    
public void printPattern(int n)
{
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j < i; j++) {
            System.out.print("*");
        }
        System.out.println();
    } System.out.println();
    
    for (int i = 1; i <= n; i++) {
        for (int j = i; j <= n; j++) {
            System.out.print("*");
        }
        System.out.println();
    } System.out.println();
    
    for (int i = 1; i <=n; i++) {
        for(int j = 1; j <= i; j++) {
            System.out.print(" ");
        }
        for (int j = i; j <= n; j++) {
            System.out.print("*");
        }
        System.out.println();
    } System.out.println();
    
    for (int i = 1; i <= n; i++) {
        for (int j = i; j <= n; j++) {
            System.out.print(" ");
        }
        for (int j = 1; j < i; j++) {
            System.out.print("*");
        }
        System.out.println();               
    }System.out.println();
 
}
    
    public void printPattern() {
        
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number of rows needed to print the pattern ");
        int rows = scanner.nextInt();
        System.out.println(" Printing the pattern ");
       
        for (int i=1; i<=rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print("*");
            }
            for (int k = i*2; k <= rows*2-1; k++)
            {
                System.out.print(" ");
            }
            for (int l = 1; l <= i; l++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
       
        for (int i=1; i<=rows-1; i++)
        {
            for (int j = rows-1; j >= i; j--)
            {
                System.out.print("*");
            }
            for (int k = 1; k <= i*2; k++)
            {
                System.out.print(" ");
            }
            for (int l = rows-1; l >= i; l--)
            {
                System.out.print("*");
            }
           
            System.out.println();
        }
        scanner.close();
        
        
}

 }

Aucun commentaire:

Enregistrer un commentaire