我无法使用for循环在Java程序中打印以下模式。 请寻求帮助。
5
54
543
5432
54321
代码
Scanner sc = new Scanner(System.in); // Taking rows value from the user
System.out.println("How many rows you want in this pattern?");
int rows = sc.nextInt();
System.out.println("Here is your pattern....!!!");
for (int i = rows; i >= 1; i--) {
for (int j = 1; j < i; j++) {
System.out.print(" ");
}
}
答案 0 :(得分:0)
尝试此代码,
public static void main(String args[]) throws Exception {
try (Scanner sc = new Scanner(System.in);) { // Taking rows value from the user
System.out.println("How many rows you want in this pattern?");
int rows = sc.nextInt();
if(rows <=0) {
System.out.println("Please enter a positive number only.");
return;
}
for (int i = 0; i < rows; i++) {
for (int j = rows; j > 0; j--) {
if (j <= i + 1) {
System.out.print(rows - j + 1);
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
打印输入5,
您要使用此模式多少行? 5
5
45
345
2345
12345
答案 1 :(得分:0)
在您当前的代码中,您只是在打印空间。现在必须更进一步,并打印数字和新行。
您可以按照以下步骤进行操作。 See it working here:
public class PattrenClass
{
public static void main(String[] args)
{
//Connecting Keyboard to Scanner with `try-with-resources`
try(Scanner sc = new Scanner(System.in);)
{
System.out.println("How many rows you want in this pattern?");
int rows = sc.nextInt(); //Taking rows value from the user
System.out.println("Here is your pattern....!!!");
for (int i = rows; i > 0; i--)
{
for (int j = 1; j < i; j++)
{
System.out.print(" ");
}
for (int j = rows; j >= i; j--)
{
System.out.print(j);
}
System.out.println();
}
}
}
}
输出:
How many rows you want in this pattern?
5
Here is your pattern....!!!
5
54
543
5432
54321