java中的循环方法(附带本人遇到的坑)

时间:2023-03-09 16:21:15
java中的循环方法(附带本人遇到的坑)

java循环结构

顺序结构的程序语句只能 被执行一次。如果你要同样的操作执行多次,就需要使用循环结构。

java中有三种主要的循环结构:
1.while 循环
2.do...while 循环
3.for 循环
  1.while循环

           while是最基本的循环,它的结构为:

 public static void main(String[] args) {
int x = 10;
while (x < 20) {
System.out.print("value of x :" + x);
x++;
System.out.print("\n");
}

  2.do…while循环

   对于while语句而言,如果不满足条件,则不能进入循环。但有时候我们需要即使不满足条件,也至少 执行一次。 
          do…while循环和while循环相同,不同的是, 
          do…while循环至少会执行一次。

public static void main(String[] args) {
int x = 10;
do {
System.out.print("value of x :" + x);
x++;
System.out.print("\n");
} while (x < 20);

  3.for循环

    虽然所有循环结构都可以用while或者do…while表示,但java提供了另一种语句(for循环),使一些循环结构变得更简单。

  public static void main(String[] args) {
for(int x=10;x<20;x=x+1){
System.out.print("value of x :"+x);
System.out.print("\n");
}

  4.增强for循环

  java5引入一种主要用于数组的增强型rot循环。 
  java增强for循环语法格式如下:

 public static void main(String[] args) {
int[] numbers = { 10, 20, 30, 40, 50 };
for (int x : numbers) {
System.out.print(x);
System.out.print(",");
}
System.out.print("\n");
String[] names = { "James", "Larry", "Tom", "Lacy" };
for (String name : names) {
System.out.print(name);
System.out.print(",");
}

  在Java8又引入一种循环方法 foreach()

重点来了,我在使用foreach时遇到了问题

代码:java中的循环方法(附带本人遇到的坑)

java中的循环方法(附带本人遇到的坑)

注意这里在foreach方法内调取外部的变量会报错,但是在普通的增强for循环中是不会报错的。

在foreach方法内调用外部变量需要用final修饰才不会报错,这里是个小坑。。。

欢迎各位大佬指点!