英文:
How can I print the pattern without filling inside of it?
问题
import java.util.Scanner;
public class Soru2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入 n 的值");
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();
}
}
}
英文:
I want to print a butterfly like this using java:
* *
** **
* * * *
* *** *
* * * *
** **
* *
However the code below prints this pattern if n=4:
* *
** **
*** ***
*******
*** ***
** **
* *
How can I print the butterfly without printing inside of it ?
I took this source code from 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
你需要在打印非边界位置时跳过打印 * 符号。
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();
}
}
}
英文:
You need to skip printing * while printing non border place
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();
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论