1、分配空间与赋值分步进行
分配空间与赋值分步进行
public class HelloWorld {
public static void main(String[] args) {
int[] a = new int[5]; //分配了长度是5的数组,但是没有赋值
// 没有赋值,那么就会使用默认值
// 作为int类型的数组,默认值是0
System.out.println(a[0]);
//进行赋值
a[0] = 100;
a[1] = 101;
a[2] = 103;
a[3] = 120;
a[4] = 140;
}
}
2、分配空间,同时赋值
分配空间,同时赋值
public class HelloWorld {
public static void main(String[] args) {
//写法一: 分配空间同时赋值
int[] a = new int[]{100,102,444,836,3236};
//写法二: 省略了new int[],效果一样
int[] b = {100,102,444,836,3236};
//写法三:同时分配空间,和指定内容
//在这个例子里,长度是3,内容是5个,产生矛盾了
//所以如果指定了数组的内容,就不能同时设置数组的长度
int[] c = new int[3]{100,102,444,836,3236};
}
}
3、练习:数组反转
首先创建一个长度是5的数组,并填充随机数。
使用for循环或者while循环,对这个数组实现反转效果
public class Reverse
{
public static void main(String[] args) {
int[] arr = new int[5];
System.out.println("数组中的各个随机数是:");
for (int i = 0; i < arr.length; i++) {
arr[i] = (int)(Math.random()*100); // 产生[0,100)的随机数
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("数组实现反转效果:");
for (int j = arr.length - 1; j >= 0; j--) {
System.out.print(arr[j] + " ");
}
}
}
// 数组反转示例
public class ArrayReverse {
public static void main(String[] args) {
int[] arr = {33, 56, 78, 90, 78};
reverseArray(arr); // 调用数组反转的方法
sortArray(arr); // 将反转后的数组通过调用排序方法进行输出
}
public static void reverseArray(int[] arr) { // 定义数组反转的方法
for (int i = 0; i <= arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
}
public static void sortArray(int[] arr){ // 定义遍历数组的方法
for (int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
}