编写一个接受整数n的程序,并以2n - 1行打印以下图片:
1 X
2 XXX
3 XXXXX
………………………………………………
2n XXXXXXXXX (2n-1 times)
………………………………………………
XXXXX
XXX
这是我拥有的代码,但它没有做到它应该做的事情,我做错了什么?我认为我需要对行做些什么,但我不确定。
import java.util.Scanner;
class a {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("enter a number: ");
int n= input.nextInt();
for(int i=0; i<n;i++){
for (int j=0; j<=i; j++)
System.out.print('X');
System.out.println();
}
{
System.out.println("enter a number: ");
int c= input.nextInt();
for(int i=0; i<c;i++){
for (int j=0; j<=i; j++)
System.out.print('X');
System.out.println();
}
}
}
}
答案 0 :(得分:0)
你的循环n次,而不是2n-1次。此外,您的打印j X,但您需要打印2n-1 X.
import java.util.Scanner;
public class a {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("enter a number: ");
int n= input.nextInt();
int lines = 2*n-1;
for(int i=1; i<=lines;i++) {
int Xs = 2 * i - 1;
int white = lines - Xs / 2;
for(int j=0; j<white;j++) System.out.print(" ");
for (int j=0; j<Xs; j++) System.out.print('X');
for(int j=0; j<white;j++) System.out.print(" ");
System.out.println();
}
for(int i=lines;i>=1;i--) {
int Xs = 2*i-1;
int white = lines - Xs / 2;
for(int j=0; j<white;j++) System.out.print(" ");
for(int j=0; j < Xs; j++) System.out.print("X");
for(int j=0; j<white;j++) System.out.print(" ");
System.out.println();
}
}
}
答案 1 :(得分:0)
这是另一种解决方案
import java.util.Scanner;
public class a {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
String accumulator = "";
for (int i = 0; i < 2 * (n - 1) + 1; i++)accumulator += "x";
String space = "";
String res = accumulator;
while (accumulator.length() > 2) {
accumulator = accumulator.substring(2);
space += " ";
res = space + accumulator + "\n" + res + "\n" + space + accumulator;
}
System.out.println(res);
}
}