簡體   English   中英

使用嵌套的for循環的簡單Java金字塔

[英]Simple Java Pyramid using nested for loops

我在嘗試找出一種使用用戶輸入來創建金字塔的方法時遇到了很多麻煩。 這是應該看起來像的樣子。

Enter a number between 1 and 9: 4
O
O
O
O
OOOO
OOOO 
OOOO 
OOOO
O
OO
OOO
OOOO

這就是我到目前為止

public static void main(String[] args) {
    int number;
    Scanner keyboard = new Scanner(System.in); 

    System.out.print("Enter a number between 1 and 9: ");
    number = keyboard.nextInt();

    for (int i = 1; i < 10; i++){
        for (int rows = number; number < i; rows++){
            System.out.print("O");
        }
        System.out.println();  
    }
}

我完全了解自己要完成的工作,但是我不完全了解for循環的工作方式。 任何幫助將不勝感激,因為我完全迷路了!

基本上for循環是這樣的

// Take this example (and also try it)
for (int i = 0; i < 10; i++) 
{
   System.out.println(i);
}


// Explanation
for(int i = 0; // the value to start at  - in this example 0
    i < 10;    // the looping conditions - in this example if i is less than 10 continue 
               //         looping executing the code inclosed in the { }
               //         Once this condition is false, the loop will exit
    i++)       // the increment of each loop - in this exampleafter each execution of the
               //         code in the { } i is increments by one
{
   System.out.println(i);  // The code to execute
}

使用不同的起始值,條件和增量進行實驗,請嘗試以下操作:

for (int i = 5; i < 10; i++){System.out.println(i);}
for (int i = 5; i >  0; i--){System.out.println(i);}

將for循環替換為:

    for (int i = 0; i < number ; i++){
        System.out.println("O");
    }
    for (int i = 0; i < number ; i++){
        for (int j = 0; j < number ; j++){
            System.out.print("O");
        }
        System.out.println();
    }
    for (int i = 1; i <= number ; i++){
        for (int j = 0; j < i ; j++){
            System.out.print("O");
        }
        System.out.println();
    }

輸出(對於數字= 6):

O
O
O
O
O
O
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
O
OO
OOO
OOOO
OOOOO
OOOOOO

一些有見識的..

for(INIT_A_VARIABLE*; CONDITION_TO_ITERATE; AN_OPERATION_AT_THE_END_OF_THE_ITERATION)
  • 您可以初始化多個變量或調用任何方法。 在Java中,您可以初始化或調用相同類型的變量/方法。

這些是有效的代碼語句:

 for (int i = 0; i <= 5; i++) // inits i as 0, increases i by 1 and stops if i<=5 is false.
 for (int i = 0, j=1, k=2; i <= 5; i++) //inits i as 0, j as 1 and k as 2.
 for (main(args),main(args); i <= 5; i++) //Calls main(args) twice before starting the for statement. IT IS NONSENSE, but you can do that kind of calls there.
 for (int i = 0; getRandomBoolean(); i++) //You can add methods to determine de condition or the after iteration statement.

現在..關於您的家庭作業..我將使用以下方式:

遍歷行的限制,並在其位置添加空格和所需字符。 位置將取決於您所在的行。

for (int i = 0; i <= 5; i++) {
  for (int j = 5; j > i; j--) {
    System.out.print(' ');
  }
  for (int j = 0; j < i; j++) {
    System.out.print("O ");
  }
  System.out.println();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM