关于for与while循环的区别我的理解

  1. 个人认为上图所述的从内存角度考虑,for循环既可以使用局部变量,也可以使用外部变量,而while循环的终止条件则必须是外部变量。下面是都是用外部变量的测试片段
@org.junit.Test
	public void testForWhile() {
          
   
		// 方式1
		int i = 5;
		for (; i < 10; i++) {
          
   
			System.out.print("-");
		}
		System.out.println(i);
		// 方式2
		int j = 5;
		while (j < 10) {
          
   
			System.out.print("-");
			j++;
		}
		System.out.println(j);
	}
	/** result:
	 -----10
     -----10	 
	 */

可见,并不是说for循环不能使用外部变量;但是for循环的确可以使用局部变量,这也是用的最频繁的方式。 2. 再者从需求场景考虑,不知道循环多少次,用while循环;知道循环次数则用for循环。这句话个人理解,for循环照样能实现while循环的需求, 测试代码如下:

@org.junit.Test
	public void testForWhile2() {
          
   
		// 方式1
		int i = 5;
		for (;true; i++) {
          
   
			System.out.print("-");
			if (i>10) {
          
   
				break;
			}
		}
		System.out.println(i);
		// 方式2
		int j = 5;
		while (true) {
          
   
			System.out.print("-");
			if (j>10) {
          
   
				break;
			}
			j++;
		}
		System.out.println(j);
	}
	/** result:
	-------11
	-------11
	 */

所以for循环能够实现while循环的功能,但while循环不能采用循环内的局部变量作为终止条件。但为什么有的时候又要用while循环呢?个人觉得是因为看起来更简洁,逻辑更清晰。

总之总结一句话,for循环与while不同在于for循环可以采用局部变量作为循环变量,除了考虑这一点,在其他功能实现上谁看起来更简洁清晰就用谁。另外还有个 do while 循环则是先执行一次再进行判断,所以该循环在先需要执行一次的情况下,代码更加简洁。

经验分享 程序员 微信小程序 职场和发展