When I recently learned Java, there was a topic:
Print - to the $ all the primes between
First Judgment -
Second Judgment 101 .... all the time.
Next to a classmate, wrote the program, found no output results, she asked me why? I had a look, and it felt like nothing.
Problem Ah, but run, is nothing output, I was depressed, then her code is this:
public class text_sushu{ /** * @param args */ public static void main (String[] args) { boolean suShu = true; for (int i = 100; i <= 200; i++) { for (int j = 2; j< i; j++) { if (i % j ==0) { suShu = false; break; } } if (SuShu) { system.out.println (i); } } }}
I was then debugged and found the problem, she put the boolean Sushu = true; This boolean variable is defined in the for-loop language
Outside of the sentence, the initial value of this Sushu is true when the For loop is entered, the first i = 100, because 100 conforms to the IF (i% J ==0) bar
The Sushu = False value is changed, the break jumps out of the loop, and the next loop, because the value of Sushu is still
False, does not conform to the following two if conditions, so until the end of the loop, the value of the Sushu is false, naturally there is no output value.
So, after the modified code is this:
public class text_sushu{ /** * @param args */ public static void main (String[] args) { for (int i = 100; i <= 200; i++) { Changes in boolean sushu = true;//location for (int j = 2; j< i; j++) { if (i % j ==0) { sushu = false; break; } } if (SuShu) { system.out.println (i); } } }}
At this point, if someone said: Bo Master the number of words, the two code basically almost. The two codes I want to say are really similar,
But I am not the number of words, the two code only one place is different, that is the boolean Sushu = true;
The above code is outside of the for statement, and the following code is inside the for statement, just because one is in the outside
Surface, but after the execution of the structure is completely different, the following code can correctly output 100~ 200 of all primes, this is why?
Since the following code enters the inner for statement, when there is a condition that conforms to the if (i% J ==0), the Sushu value becomes flase,
However, when the inner loop is over, and back to the outer loop, the value of the Sushu is set to true, which ensures that the code executes correctly.
This is a question I encountered when I was learning Java, and I hope to be helpful to beginners in Java.
This article is from the "frequently asked questions in Java" blog, so be sure to keep this source http://liwei9455.blog.51cto.com/10104268/1631064
Changes to variables in Java, resulting in change in output results