First of all, there is no difficulty in this, which is to analyze the difference between break and return. From the final printing results, we can see:
1. Break just jumps out of the loop and continues to execute code inside and outside the function.
2. Return is a direct function that returns, and the code in the loop and the following function will not be executed.
Code:
package ; /** * 8. Write a program first and print the values from 1 to 100. Then modify the program and use the break keyword to exit when it prints to 98. Then try to use return to achieve the same purpose. * @author 281167413@ */ public class Test8 { public static void main(String[] args) { nomDisplay(); breakDisplay(); returnDisplay(); } public static void nomDisplay() { for(int i=1; i<=100; i++) { (i); } (" nom end!\n"); } public static void breakDisplay() { for(int i=1; i<=100; i++) { if (98 == i) { break; } (i); } (" break end!\n"); } public static void returnDisplay() { for(int i=1; i<=100; i++) { if (98 == i) { return; } (i); } (" return end!\n"); } }
Print result:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 nom end! 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 break end! 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697