Как я могу напечатать шаблон без заполнения внутри него? - PullRequest
0 голосов
/ 03 мая 2020

Я хочу напечатать такую ​​бабочку, используя java:

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

Однако приведенный ниже код печатает этот шаблон, если n = 4:

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

Как мне напечатать бабочка без печати внутри нее? Я взял этот исходный код от http://solvedpatterns.blogspot.com/2016/07/ButterFly.html

import java.util.Scanner;
public class Soru2 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter n value");
        int n=sc.nextInt();
        int sp=2*n-1;
        int st=0;
        for(int i=1;i<=2*n-1;i++){
            if(i<=n){
                sp=sp-2;
                st++;
            }
            else{
                sp=sp+2;
                st--;
            }
            for(int j=1;j<=st;j++){
                System.out.print("*");
            }
            for(int k=1;k<=sp;k++){
                System.out.print(" ");
            }
            for(int l=1;l<=st;l++){
                if(l!=n)
                    System.out.print("*");
            }
            System.out.println();
        }
    }
}

1 Ответ

1 голос
/ 03 мая 2020

Вам нужно пропустить печать * при печати без полей

package com.practice;

import java.util.Scanner;
public class Soru2 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter n value");
        int n=sc.nextInt();
        int sp=2*n-1;
        int st=0;
        for(int i=1;i<=2*n-1;i++){
            if(i<=n){
                sp=sp-2;
                st++;
            }
            else{
                sp=sp+2;
                st--;
            }
            for(int j=1;j<=st;j++){
                if(j==1 || j==st || (((j+1)==st) && i==n)) // add this
                    System.out.print("*");
                else // add this
                    System.out.print(" ");
            }
            for(int k=1;k<=sp;k++){
                System.out.print(" ");
            }
            for(int l=1;l<=st;l++){
                if(l==1 || l==st || (((l-1)==st) && i==n)) { // add this
                    if (l != n)
                        System.out.print("*");
                }
                else // add this
                    System.out.print(" ");
            }
            System.out.println();
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...