我想用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();
}
}
}发布于 2020-05-04 00:29:55
在打印非边框位置时,需要跳过打印*
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();
}
}
}https://stackoverflow.com/questions/61577451
复制相似问题