帮助理解 java 'for' 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5162845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:45:53  来源:igfitidea点击:

Help with understanding java 'for' loops

javaloopsfor-loop

提问by jona

I have to write a java program where the solution will include the printing of the arrow tip figure depending on the number of rows. Below are example of how the result should look. However, I cannot do this until I understand for loops. I know I have to work with the rows and columns and possibly nested loops. I just dont know how to connect the row with the columns using for loops. Please help me in understanding these loops. Thanks!

我必须编写一个 java 程序,其中解决方案将包括根据行数打印箭头提示图。下面是结果应该如何显示的示例。但是,在我理解 for 循环之前,我不能这样做。我知道我必须处理行和列以及可能的嵌套循环。我只是不知道如何使用 for 循环将行与列连接起来。请帮助我理解这些循环。谢谢!

Example #1 (odd number of rows)

Example #1(奇数行)

>
>>>
>>>>>
>>>>>>>
>>>>>
>>>
>

Example #2 (even number of rows)

示例 #2(偶数行)

>
>>>
>>>>>
>>>>>>>
>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>>>
>>>>>>>>>
>>>>>>>
>>>>>
>>>
>

回答by Orbit

a for loop will loop through a collection of data, such as an array. The classic for loop looks like this:

for 循环将遍历数据集合,例如数组。经典的 for 循环如下所示:

  for(counter=0;counter <= iterations;counter++){   }

the first param is a counter variable. the second param expresses how long the loop should last, and the 3rd param expresses how much the counter should be incremented by after each pass.

第一个参数是一个计数器变量。第二个参数表示循环应该持续多长时间,第三个参数表示每次通过后计数器应该增加多少。

if we want to loop from 1 - 10, we do the following:

如果我们想从 1 - 10 循环,我们执行以下操作:

for(counter=1;counter<=10;counter++){ System.out.println(counter); }

if we want to loop from 10 - 1, we do the following:

如果我们想从 10 - 1 循环,我们执行以下操作:

for(counter=10;counter>=1;counter--){  System.out.println(counter); }

if we want to loop through a 2 dimensional collection, like...

如果我们想遍历一个二维集合,比如......

1 2 3
4 5 6
7 8 9

int[][] grid = new int[][] {{1,2,3},{4,5,6},{7,8,9}};

we need 2 loops. The outer loop will run through all the rows, and the inner loop will run through all the columns.

我们需要2个循环。外循环将运行所有行,内循环将运行所有列。

you are going to need 2 loops, one to iterate through the rows, one to iterate through the columns.

您将需要 2 个循环,一个循环遍历行,一个循环遍历列。

 for(i=0;i<grid.length;i++){
    //this will loop through all rows...
    for(j=0;j<grid[i].length;j++){
      //will go through all the columns in the first row, then all the cols in the 2nd row,etc
      System.out.println('row ' + i + '-' + 'column' + j + ':' + grid[i][j]);
    }
 }

In the outer loop, we set a counter to 0 for the first parameter. for the second, to calculate how many times we will loop, we use the length of the array, which will be 3, and for the third param, we increment by one. we can use the counter, i, to reference where we are inside the loop.

在外循环中,我们将第一个参数的计数器设置为 0。对于第二个参数,为了计算循环次数,我们使用数组的长度,即 3,对于第三个参数,我们增加 1。我们可以使用计数器 i 来引用我们在循环中的位置。

We then determine the length of the specific row by using grid[i].length. This will calculate the length of each row as they are being looped through.

然后我们使用 grid[i].length 确定特定行的长度。这将计算每行循环时的长度。

Please feel free to ask any questions you may have regarding for loops!

请随时提出有关 for 循环的任何问题!

EDIT: understanding the question.....

编辑:理解问题.....

You are going to have to do several things with your code. Here we will store the number of lines in a variable, speak up if you need to pass in this value to a method.

您将不得不对您的代码做几件事。在这里,我们将在变量中存储行数,如果您需要将此值传递给方法,请说出来。

 int lines = 10; //the number of lines
 String carat = ">";

 for(i=1;i<=lines;i++){
     System.out.println(carat + "\n"); // last part for a newline
     carat = carat + ">>";
 }

The above will print out carats going all the way up. We print out the carat variable then we make the carat variable 2 carats longer.

以上将打印出克拉数一直上升。我们打印出克拉变量,然后我们使克拉变量长 2 克拉。

.... the next thing to do is to implement something that will decide when to decrease the carats, or we can go up half of them and down the other half.

....接下来要做的是实施一些决定何时减少克拉的事情,或者我们可以增加一半,减少另一半。

Edit 3:

编辑3:

Class Test {
    public static void main(String[] args) {

        int lines = 7; 

        int half = lines/2;
        boolean even = false;
        String carat = ">";
        int i;

        if(lines%2==0){even = true;} //if it is an even number, remainder will be 0

        for(i=1;i<=lines;i++){
                System.out.println(carat + "\n");                           
                if(i==half && even){System.out.println(carat+"\n");} // print the line again if this is the middle number and the number of lines is even
                if(((i>=half && even) || (i>=half+1)) && i!=lines){ // in english : if the number is even and equal to or over halfway, or if it is one more than halfway (for odd lined output), and this is not the last time through the loop, then lop 2 characters off the end of the string
                        carat = carat.substring(0,carat.length()-2); 
                }else{ 
                        carat = carat + ">>"; //otherwise, going up
                }
        }
    }
}

Explanation and commentary along shortly. Apologies if this is over complicated (i'm pretty sure this is not even close to the best way to solve this problem).

解释和评论很快。如果这过于复杂,我很抱歉(我很确定这甚至不是解决这个问题的最佳方法)。

Thinking about the problem, we have a hump that appears halfway for even numbers, and halfway rounded up for the odd numbers.

考虑这个问题,我们有一个驼峰,偶数出现在一半,奇数出现一半。

At the hump, if it is even, we have to repeat the string.

在驼峰处,如果是偶数,我们必须重复字符串。

We have to then start taking off "<<" each time, since we are going down.

然后我们每次都必须开始起飞“<<”,因为我们正在下降。

Please ask if you have questions.

如果您有问题,请提问。

回答by Eric Gross

I had the same question for a homework assignment and eventually came to a correct answer using a lot of nested if loops through a single for loop.

我对家庭作业有同样的问题,最终通过单个 for 循环使用大量嵌套的 if 循环得出了正确的答案。

There is a lot of commenting throughout the code that you can follow along to explain the logic.

整个代码中有很多注释,您可以按照这些注释来解释逻辑。

class ArrowTip {

public void printFigure(int n) {      //The user will be asked to pass an integer that will determine the length of the ArrowTip
 int half = n/2;   //This integer will determine when the loop will "decrement" or "increment" the carats to String str to create the ArrowTip
 String str = ">";  //The String to be printed that will ultimately create the ArrowTip
 int endInd;        //This integer will be used to create the new String str by creating an Ending Index(endInd) that will be subtracted by 2, deleting the 2 carats we will being adding in the top half of the ArrowTip

 for(int i = 1; i <= n; i++) {       //Print this length (rows)
    System.out.print(str + "\n");   //The first carat to be printed, then any following carats.
    if (n%2==0) {       //If n is even, then these loops will continue to loop as long as i is less than n.
      if(i <= half) {     //This is for the top half of the ArrowTip. It will continue to add carats to the first carat
         str = str + ">>";    //It will continue to add two carats to the string until i is greater than n.
      }
      endInd = str.length()-2;  //To keep track of the End Index to create the substring that we want to create. Ultimately will determine how long the bottom of the ArrowTip to decrement and whether the next if statement will be called.
      if((endInd >= 0) && (i >= half)){   //Now, decrement the str while j is greater than half
         str = str.substring(0, endInd);  //A new string will be created once i is greater than half. this method creates the bottom half of the ArrowTip
      }
    }
    else {          //If integer n is odd, this else statement will be called.
      if(i < half+1) {  //Since half is a double and the integer type takes the assumption of the one value, ignoring the decimal values, we need to make sure that the ArrowTip will stick to the figure we want by adding one. 3.5 -> 3 and we want 4 -> 3+1 = 4
          str = str + ">>"; //So long as we are still in the top half of the ArrowTip, we will continue to add two carats to the String str that will later be printed.
       }
      endInd = str.length()-2;      //Serves the same purpose as the above if-loop when n is even.
       if((endInd >= 0) && (i > half)) {  //This will create the bottom half of the ArrowTip by decrementing the carats.
        str = str.substring(0, endInd);   //This will be the new string that will be printed for the bottom half of the ArrowTip, which is being decremented by two carats each time.
      }
    }
 }
}
}

Again, this was for a homework assignment. Happy coding.

同样,这是一个家庭作业。快乐编码。

回答by atwologa

Here is a simple answer for you hope it helps! Cheers Logan.

以上是简单的回答,希望对你有帮助!干杯洛根。

public class Loop {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            int count = i;
            int j = 0;

            while (j != count) {
                System.out.print(">");
                j++;
            }
            System.out.println();

        }
        for (int i = 10; i > 0; i--) {
            int count = i;
            int j = 0;

            while (j != count) {
                System.out.print(">");
                j++;
            }
            System.out.println();

        }
    }
}