java prints values from 1 to 100 of break return sentence breaks

  • 2020-06-12 09:03:40
  • OfStack

First of all, there is no difficulty in this. It is to analyze the effect of break and return. It can be seen from the final printing results:

break simply breaks out of the loop and continues to execute code inside and outside the loop.
2, return is a direct function return, the loop and the function of the following code will not be executed.

Code:


package com.itheima;

/**
 * 8 ,   write 1 A program to print from 1 to 100 The value of the. After modifying the program by using break Keywords that make the program in print to 98 When to exit. And then try to use return To achieve the same goal. 
 * @author 281167413@qq.com
 */

public class Test8 {
	
	public static void main(String[] args)
	{
		nomDisplay();
		breakDisplay();
		returnDisplay();
	}
	
	public static void nomDisplay()
	{
		for(int i=1; i<=100; i++)
		{
			System.out.print(i);
		}
		System.out.print(" nom end!\n");
	}

	public static void breakDisplay()
	{
		for(int i=1; i<=100; i++)
		{
			if (98 == i)
			{
				break;
			}
			System.out.print(i);
		}
		System.out.print(" break end!\n");
	}

	public static void returnDisplay()
	{
		for(int i=1; i<=100; i++)
		{
			if (98 == i)
			{
				return;
			}
			System.out.print(i);
		}
		System.out.print(" return end!\n");
	}
}

Print results:


123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 nom end!
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 break end!
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697


Related articles: