Java入门-循环

自增和自减

数组

数组就是一组类型相同的数组合在一起

// 声明一个 int 数组的变量,数组大小为6
int[] numbers = new int[6];
// 声明一个 int 数组的变量,数组大小为6
int[] numbers = new int[6];

numbers[0] = 1;
numbers[1] = 3;
numbers[2] = 5;
numbers[3] = 7;
numbers[4] = 9;
numbers[5] = 11;
// 得到数组中第三个数字
int num = numbers[2];
System.out.println(num);

长度

数组对象都有一个值length,可以得到这个数组的长度。

public static void main(String[] args) {
  int[] numbers = new int[8];

  int size = numbers.length;
  System.out.println(size);

}
//输出8

初始化变量

public static void main(String[] args) {
  int[] numbers = new int[8];
}

上面的代码就是对数组进行了初始化,这个初始化的作用就是开辟该长度的存储空间。

数组初始化后还没有赋值,这个时候int类型默认是0,String类型默认是null。

使用for循环

public static void main(String[] args) {
  String[] tables = new String[3];

  tables[0] = "张三";
  tables[1] = "李四";
  tables[2] = "王五";

  for(int i = 0; i < tables.length; i++){
    String name = tables[i];
    System.out.println(i+":"+name);
  }

}

上面的代码可以简化一下:


public static void main(String[] args) {
  String[] tables = new String[]{"张三","李四", "王五"};

  for(int i = 0; i < tables.length; i++){
    String name = tables[i];
    System.out.println(i+":"+name);
  }

}

举例:用for循环输出99乘法表

public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "×" + i + "=" + i * j + "\t");
            }
            System.out.println();
        }
    }
}

for循环还有另一种形式:

增强for循环是JDK1.5以后出来的一个高级for循环,专门用来遍历数组和集合的。它的内部原理其实是个Iterator迭代器,所以在遍历的过程中,不能对集合中的元素进行增删操作。

格式:

for(元素的数据类型 变量 : Collection集合or数组){
}

练习一:遍历数组

int[] arr = new int[]{11,22,33};
for (int n : arr) {
    //变量n代表被遍历到的数组元素</span>
    System.out.println(n);
}

练习二:遍历集合

Collection<String> coll = new ArrayList<String>();
coll.add("a1");
coll.add("a2");
coll.add("a3");
coll.add("a4");
for(String str : coll){
    //变量Str代表被遍历到的集合元素</span>
    System.out.println(str);
}

增强for循环和老式的for循环有什么区别?

注意:新for循环必须有被遍历的目标。目标只能是Collection或者是数组。

建议:遍历数组时,如果仅为遍历,可以使用增强for如果要对数组的元素进行 操作,使用老式for循环可以通过角标操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值