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");
}
}
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
There will be ghosts when you jump out. . . .
i -= 5;
Is it wrong?Every time through the loop,
i++
increasesi
by 1, buti -= 5
; also decreasesi
by 5.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
...
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
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
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.
Logic problem, infinite loop
For this kind of question, it is recommended to find an introductory book or watch an introductory video for 10 minutes