[英]Pattern formation using Java
我正在嘗試使用Java在倒三角形中打印數字模式。 我已經使用不同的條件嘗試了很多次,但是無法獲得完全相同類型的模式。 有時數字的順序被更改,或者有時數字被更改之前的空格數。 這是我的代碼的基本結構:
import java.io.*;
import java.util.*;
class S
{
public static void main (String args [])
{
int no = (int)(Math.random() * 10);
for (int x = no; x >= 1; x--)
{
for (int y = no; y >= 1; y--)
{
if ()
System.out.print(y) ;
else ()
System.out.print (" ");
}
System.out.println();
}
}
}
預期結果是:
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
我不能讓將要來的,如果和其他合適的條件。 我嘗試了很多,但無法獲得以下模式。
我們如何在Java中打印這樣的模式
有人可以建議在if和else編碼中應該包含什么才能得到這種模式。
實際上,您不需要任何特殊條件,只需使用循環即可回答您的問題。
for(int i=0; i< no; i++){
for(int j=no; j>i; j--){
System.out.print(j+ " ");
}
System.out.println();
}
這應該給您正確的輸出,現在您要做的就是格式化。
檢查此:::只需添加一個特殊的整數i:
import java.io.*;
import java.util.*;
class S
{
public static void main (String args [])
{
int no = (int)(Math.random() * 10);
int i = 0;
for (int x = no; x >= 1; x--)
{
for (int y = no; y >= 1; y--)
{
if (x > y){
System.out.print((y+i)+" ") ;
}
else{
System.out.print (" ");
}}
System.out.println();
i++;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.