Java 循环结构
在Java中,循环主要只有两种,一个是for,另外一个就是while
Java for 使用
第一种方式, 有下标,再根据下标获取对应的value
public class TestFor1 {
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
// 注意,条件只要成立就进入循环体,或则就退出
for(int i = 0; i < array.length; i ++)
{
int value = array[i];
System.out.println("[" + i + "] = " + value);
}
}
}
输出结果
[0] = 1
[1] = 2
[2] = 3
第二种方式 for(:), 表示不要下标,只要value
public class TestFor2 {
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
//
for(int value : array)
{
System.out.println("rs = " + value);
}
}
}
输出结果
rs = 1
rs = 2
rs = 3
for(int value:array)表示先设置一个与value数组里的元素相同的变量,这个变量先等于value数组的第一个元素,然后进入循环体, 第二次循环就等于a数组的第二个元素,进入循环体,以此类推。
Java while 使用
简单while的使用
public class TestWhile {
public static void main( String[] args )
{
int[] array = new int[] {1, 2, 3};
int len = array.length;
int index = 0;
// 注意这里只能是一个条件的,条件成立就进入循环体,或则就退出
while(index < len)
{
int value = array[index];
System.out.println(" index = " + index + ", value = " + value);
index ++;
}
}
}
输出结果
index = 0, value = 1
index = 1, value = 2
index = 2, value = 3
do-while使用,
public class TestDoWhile()
{
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
int len = array.length;
int index = 0;
do {
// 先进入循环体
int value = array[index];
System.out.println(" index = " + index + ", value = " + value);
index ++;
}while(index < len);
}
}
输出结果
index = 0, value = 1
index = 1, value = 2
index = 2, value = 3
这种方式是先执行一次循环,再进行条件判断,而之前都是先判断条件,再决定是否进入循环
Java 循环常见问题
- 数组越界
- 死循环
我们看看下面这个例子,只是多了个 = 号
public class TestDoWhile()
{
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
int len = array.length;
int index = 0;
do {
// 先进入循环体
int value = array[index];
System.out.println(" index = " + index + ", value = " + value);
index ++;
// 错误点在这里,由于是先执行一次循环,然后这里又是<=,所以就多执行了一次,自然就越界了
}while(index <= len);
}
}
输出结果
index = 0, value = 1
index = 1, value = 2
index = 2, value = 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
我们再看看死循环(我保证,执行下面两个,让你的电脑直接卡死)
public class Test1
{
public static void main(String[] args) {
boolean flag = true;
int index = 0;
do {
System.out.println("index = " + index);
}while(flag);
}
}
或者
public class Test2
{
public static void main(String[] args) {
boolean flag = true;
int index = 0;
while(flag)
{
System.out.println("index = " + index);
}
}
}
Java 如何防止或着降低死循环呢?
- 使用final,禁止重新赋值
public class Test
{
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
for(final int value : array)
{
// 编译时出错,提示 The final local variable value may already have been assigned
value = 3;
}
}
}
- 循环体里面尽量不要超过三层嵌套,如果有多于三个,最好分离,并抽出来单独为一个方法体
- 养成好的编程习惯; 一个优秀的程序员,一定有一个良好的编程习惯。