Java 我正在尝试编写一个接受整数n并打印具有2n–1行的下图的程序:
编写一个接受整数n的程序,并用2n–1行打印以下图片:Java 我正在尝试编写一个接受整数n并打印具有2n–1行的下图的程序:,java,loops,for-loop,rows,Java,Loops,For Loop,Rows,编写一个接受整数n的程序,并用2n–1行打印以下图片: 1 X 2 XXX 3 XXXXX ……………………………………………… 2n XXXXXXXXX (2n-1 times) ……………………………………………… XXXXX XXX 这是我的代码,但它没有做它应该做的,我做错了什么?我想我需要对这些行做些什么,但我不确定 import java.util.Scanner; class a { public static
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();
}
}
}
}
你的循环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();
}
}
}
这里有另一个解决方案
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);
}
}
它没有做它应该做的事情它在做什么?你真的确定要打印2n-1行吗?不是n行吗?在主方法中,我在下半部分看到了一个不必要的{}。我曾经有过这样的编程赋值。@user3380761堆栈溢出不是这样工作的。如果您有自己无法解决的特定问题,您需要向我们提供尽可能多的信息。如果你不想问一个好问题,我们为什么要做任何工作来帮助你回答?