使用嵌套for循环的简单Java金字塔

时间:2013-10-01 01:11:02

标签: java for-loop

我在尝试找出使用用户输入创建金字塔的方法时遇到了很多麻烦。这就是它的样子。

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循环是如何工作的。任何帮助都会非常感激,因为我完全迷失了!

3 个答案:

答案 0 :(得分:1)

基本上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);}

答案 1 :(得分:0)

将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();
    }

OUTPUT(数字= 6):

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

答案 2 :(得分:0)

一些洞察力......

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();
}