search

Home  >  Q&A  >  body text

java - Why can't I break out of this loop?

1. Problem description: Keep in an infinite loop, printing repeatedly until an error occurs

2.Related code

int[] Aarray = new int[]{2,4,5,6,2};
int[] Barray = new int[]{3,6,2,4,6};

for (int i = 0 ;i < 10 ;i ++ )
{
    if (i < 5)
    {
        System.out.print(Aarray[i] + "\t");
    }
    
    else
    {    
        i -= 5;
        System.out.print(Barray[i] + "\t");
    }
}


扔个三星炸死你扔个三星炸死你2747 days ago851

reply all(9)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-12 09:23:20

    When i = 1, 2, 3, 4, let’s not talk about it anymore, print 1 2 3 4
    When i = 5, enter the else statement block
    i -= 5, which is i = i-5. The result is i = 0, then i++

    Then i starts looping from 1 again. The termination condition of the for loop i < 10 can never terminate

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-12 09:23:20

    There will be ghosts when you jump out. . . .

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-12 09:23:20

    i -= 5; Is it wrong?

    Every time through the loop, i++ increases i by 1, but i -= 5; also decreases i by 5.

    reply
    0
  • 怪我咯

    怪我咯2017-06-12 09:23:20

    When

    i=5, if does not hold, enter else,
    finish i -= 5; the result is i=0;
    then exit else, after i++, i=1;
    enter if
    ...
    when i= 5 o'clock
    ...

    reply
    0
  • 高洛峰

    高洛峰2017-06-12 09:23:20

    Simple, you will understand after you run through the program in your mind. At the beginning i=0, which is less than 5, output, then i++ reaches 1, continue to be less than 5, and output, and continue like this until i=5, then i<5 If it is not established, take the else branch, i-=5; i is less than 0 again, and then it starts to enter the next loop like the beginning, so there is an infinite loop

    reply
    0
  • 欧阳克

    欧阳克2017-06-12 09:23:20

    If you look at the situation of each value of i, it will be clear at a glance. When i>5, i enters else. At this time, i becomes 0 again, which means that i will never reach the end of i>10. Loop conditions

    reply
    0
  • 某草草

    某草草2017-06-12 09:23:20

    The logic is wrong. After adding to 6, subtract 5 again, returning to 1, and then add 1 each time. After adding to 6, subtract 5 again, returning to 1, and the cycle continues.

    reply
    0
  • ringa_lee

    ringa_lee2017-06-12 09:23:20

    Logic problem, infinite loop

    reply
    0
  • 迷茫

    迷茫2017-06-12 09:23:20

    For this kind of question, it is recommended to find an introductory book or watch an introductory video for 10 minutes

    reply
    0
  • Cancelreply