[英]How can I print the following pattern using nested for loops in JAVA?
我無法使用 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(" ");
}
}
試試這個代碼,
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
在您目前的代碼中,您只是在打印空間。 現在必須更進一步,打印數字和新行。
您可以按照以下方式進行。 看到它在這里工作:
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
這段代碼正在工作......我已經自己測試過了。 如有任何疑問,歡迎隨時提問😃。
import java.util.Scanner;
public class pattern_54321
{
public static void main (String args[])
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the number of rows -");
int r=sc.nextInt();
System.out.println("Here is your required pattern -");
int i=0,j=0,k=0,n=r;
for(i=r;i>=1;i--)
{
for(k=n;k>=1;k--)
{
System.out.print(" ");
}
for(j=r;j>=i;j--)
{
System.out.print(j);
}
System.out.println();
n--;
}
}
}
您可以在下面看到 BlueJ 終端窗口屏幕截圖 -
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.