P1-11 数组其他

数组其他

一切类型皆可数组

  • 1、String[] a=new String[10];
    • String[] a={“ccc”,”yyds”,”rzx”};
  • 2、byte[] bytes=new byte[];
    • byte[] bytes={3,5,7,9,10,12};

数组长度

  • 1、数组有一个特殊的用法是:数组名.length
  • 这样可以获得数组的长度,这样可以避免上面吧数组长度写死的问题
    • int len =al.length
  • 2、避免魔法数
1
2
3
4
5
6
int[] sums ={33,66,88,333,666,888};
//从第0个元素,遍历到第“6-1”个元素 这个6就是所谓的魔法数~
for (int i= 0;i<=6-1;i++)
{
System.out.println(sums[i]);
}

案例1:数组的正序遍历

写法1

1
2
3
4
5
6
int[] sums ={33,66,88,333,666,888};
//从第0个元素,遍历到第“length-1”个元素
for (int i= 0;i<=sums.length-1;i++)
{
System.out.println(sums[i]);
}

写法2

1
2
3
4
5
int[] sums ={33,66,88,333,666,888};
for (int i= 0;i<sums.length;i++)
{
System.out.println(sums[i]);
}

案例2:数组倒序遍历

1
2
3
4
5
6
int[] sums ={33,66,88,333,666,888};
//从第“length-1”个元素,遍历到第0个元素
for (int i= sums.length-1;i>=0;i--)
{
System.out.println(sums[i]);
}

增强for循环

增强for循环

1
2
3
4
5
int[] sums ={33,66,88,333,666,888};
for (int n:sums)//遍历nums的每个元素,每个遍历到的元素用变量n来获取,对于每个遍历到的元素,都执行一次循环体
{
System.out.println(n);
}

数组的打印

数组的打印

  • 练习
    1
    2
    3
    4
    String[] strs={"rzx","nzs","18"};
    System.out.println(strs);
    String str1 = Arrays.toString(strs);//把数组转换为“可读性强”的字符串
    System.out.println(str1);

数组打印


P1-11 数组其他
http://example.com/2024/08/01/SE101-零基础玩Java/Part1-笔记/P1-11 数组其他/
Author
John Doe
Posted on
August 1, 2024
Licensed under