1

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

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 循环是如何工作的。任何帮助将不胜感激,因为我完全迷路了!

4

3 回答 3

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);}
于 2013-10-01T01:23:07.997 回答
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();
}
于 2013-10-01T01:45:39.767 回答
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();
    }

输出(数字 = 6):

O
O
O
O
O
O
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
O
OO
OOO
OOOO
OOOOO
OOOOOO
于 2013-10-01T01:28:02.653 回答