(Java)while循环

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011978079/article/details/89508633

语法格式:

while(循环条件)
{
    语句;
}

执行流程:

package www.example.com;

public class WhileDemo {
	/*
	 * n的值必须先进行初始化
	 * 循环变量n的值必须被 改变
	 * */
	public static void main(String[] args) {
		int n = 1;
		while (n<5) {
			n++;
			System.out.println(n);
		}
	}

}


//输出
2
3
4
5

示例一:

package www.example.com;

public class WhileDemo {

	public static void main(String[] args) {
		int k = 10;
		while(k==0)
		{
			k = k-1;
			System.out.println(k);
		}
	}
	
}

//输出

循环语句一次也不执行

示例二:

package www.example.com;

public class WhileDemo {

	public static void main(String[] args) {
		int m = 3, n = 6, k = 0;
		while(m<n)
		{
			++k;m++;--n;
			System.out.println(k);
		}
	}
	
}
//输出
1
2

示例三:

package www.example.com;

public class WhileDemo {

	public static void main(String[] args) {
		int j = 9, i = 6;
		while(i-- > 3)
		{
			--j;
			System.out.println(j);
		}
	}
	
}

//输出
8
7
6

案例一:

package www.whiledemo.com;

public class PlusDemo1_5 {

	/*
	 * 求1到5的累加和
	 * 1+2+3+4+5
	 * */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int n = 1;
		int sum = 0;
		while (n<=5)
		{
			sum += n;
			n++;
		}
		System.out.println(sum);
	}

}

//输出
15

猜你喜欢

转载自blog.csdn.net/u011978079/article/details/89508633