02数组和字符串

02数组和字符串,第1张

02数组和字符串

文章目录
  • 数组的创建
  • 数组的遍历

数组的创建

方法一:

package cn.xu.arrays;
import java.util.Arrays;


public class Example2 {
    public static void main(String[] args) {
        int[] ns;
        ns = new int[5];
        System.out.println(ns[0]);
    }
}

方法二:
初始化并且赋值,把[]的数字去掉,让编译器计算有多少个值,new可以省略掉编译器会给我们加上,这是一种语法糖。

package cn.xu.arrays;
import java.util.Arrays;


public class Example2 {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6};
//      int[] a = new int[] {1,2,3,4,5,6};
        System.out.println(a[0]);
    }
}
数组的遍历

第一种:用for循环遍历

package cn.xu.arrays;
import java.util.Arrays;

public class Example2 {
    public static void main(String[] args) {
        int[] a = new int[] {1,2,3,4,5,6};
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}

第二种:类似迭代器

package cn.xu.arrays;
import java.util.Arrays;

public class Example2 {
    public static void main(String[] args) {
        int[] a = new int[] {1,2,3,4,5,6};
        for (int n : a){
            System.out.println(n);
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5693307.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存