【Java数组笔记】4-2 数组的使用
§4-2 数组的使用
现在我们已经引入了数组的概念,接下来我们将通过一个例子在看看数组的使用。
4-2.1 数组的使用方式
一般地,数组的使用有以下方式:
-
普通的
for
循环; -
for-each
循环(增强型for
循环); -
数组作为方法入参;
-
数组作为返回值。
那么接下来,我们将通过几个例子,来上手数组的使用。
4-2.2 实例
4-2.2.1 打印数组中所有的元素
这个实例我们已经在上一节中已经提及,我们可以使用for
语句遍历数组即可。
for (int x : <arrays>) {
System.out.println(x)
}
利用增强型for
循环遍历数组的一个优势在于,这种方法不需要理会下标,通常用于处理结果。但若要对数组中具体的元素进行操作,则普通的for
循环可能更为适合。
我们也可以将其写成方法:
public static void PrintArrays(int[] arrays) {
for (int x : arrays) {
System.out.print(x+"\t")
}
}
这个方法我们稍后会用到。
4-2.2.2 计算数组中所有元素之和与最值
同样地,我们也需要通过for
循环遍历数组中每一个元素以实现它。
int sum = 0;
for (int i = 0; i < arrays.length; i++) {
sum += arrays[i]
}
System.out.println("The sum is "+sum)
输出数组中元素最值
int max = arrays[0];
int min = arrays[0];
for (int i = 1; i < arrays.length ; i++) {
if ( max < arrays[i] ) {
max = arrays[i];
}
if ( min > arrays[i] ) {
min = arrays[i];
}
}
System.out.print("The maximun is "+max+", and the minimun is "+min+". ")
4-2.2. 3 反转数组元素并输出
这里,我们同样通过for
循环来实现。
public class Reversal {
public static void main(String[] args) {
int[] arrays = {1,2,3,4,5};
printArrays(reverse(arrays));
//直接打印数组会输出其对象地址。
}
//反转数组(以整型数组为例)
public static int[] reverse(int[] arrays) {
int[] result = new int[arrays.length];
for (int i = arrays.length - 1, j = 0; j < result.length ; i--, j++) {
result[j] = arrays[i];
}
return result;
}
public static void printArrays(int[] arrays) {
for (int i : arrays) {
System.out.print(i+"\t");
}
}
}
在这里,我们就需要在for
循环的初始化变量和迭代上多增加一变量以满足需求,不同变量和条件用逗号隔开即可。
编译并运行,得到结果如图所示:
也可以通过找到规律,直接反转数组。
不难发现,交换次数是原数组长足的一半,且交换时,两个元素的下标之和为数组长度 - 1。
import java.util.Arrays;
public class Reversal {
public static void main(String[] args) {
int[] arr = {11,22,33,44,55,66};
int temp = 0;
System.out.println("原数组:");
System.out.println(Arrays.toString(arr)); //使用 Arrays 工具类将数组打印为字符串
int len = arr.length;
for (int i = 0; i < arr.length / 2; i++) {
temp = arr[len - i - 1];
arr[len - 1 - i] = arr[i];
arr[i] = temp;
}
System.out.println("反转后:");
System.out.println(Arrays.toString(arr));
}
}
运行,得到结果:
原数组:
[11, 22, 33, 44, 55, 66]
反转后:
[66, 55, 44, 33, 22, 11]
4-2.2.4 扩容数组,由用户决定何时终止输入
数组一旦创建完成,其容量不可变。要想扩容数组,应当新建一个新的数组,在新的数组上操作后,再让原数组的引用变量指向新数组即可。
注意:由于 Scanner
类对象十分容易抛出异常,这里使用到了后续章节中异常处理的部分。(同下)
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArrayAdd {
public static void main(String[] args) {
//数组扩容:由用户决定添加数目
//假设原始数组为
int[] arr = {1,2,3};
//用户决定添加:接受用户输入 -> 判断 -> 是:
//创建新数组,长度比原数组大1,并将原数组内容拷贝至新数组
//然后,在末尾接受新的元素
//最后,再让原始数组的引用变量指向新数组
Scanner scanner = new Scanner(System.in);
String str = null;
System.out.println("原始数组:" + Arrays.toString(arr));
while (true) {
System.out.println("是否添加元素(y/n)?:");
try {
str = scanner.nextLine();
} catch (Exception exception) { //主要用于防止 NoSuchElementException
System.out.println("发生异常,请重新输入。");
scanner = new Scanner(System.in);
System.gc();
continue;
}
if (str.equals("y") || str.equals("Y")) {
//新建新的数组,并拷贝原有数组内容
int[] newArr = new int[arr.length + 1];
for (int i = 0; i < arr.length; i++) {
newArr[i] = arr[i];
}
int newInt = 0;
System.out.println("请输入新的元素:");
//可能异常处理
while (true) {
try {
newInt = scanner.nextInt();
break;
} catch (InputMismatchException exception) {
System.out.println("输入有误,请重新输入。");
scanner = new Scanner(System.in);
System.gc();
} catch (Exception exception) {
System.out.println("发生异常,请重新输入。");
scanner = new Scanner(System.in);
System.gc();
} finally {
scanner.nextLine(); //读取回车,防止跳过输入
}
}
newArr[newArr.length - 1] = newInt;
arr = newArr;
System.out.println("扩容结束,新的数组为:" + Arrays.toString(arr));
continue;
} else if (str.equals("n") || str.equals("N")) {
System.out.println("原数组不变:" + Arrays.toString(arr));
break;
} else {
System.out.println("输入有误,请重新输入。");
continue;
}
}
scanner.close();
}
}
运行,得到:
原始数组:[1, 2, 3]
是否添加元素(y/n)?:
y
请输入新的元素:
4
扩容结束,新的数组为:[1, 2, 3, 4]
是否添加元素(y/n)?:
y
请输入新的元素:
5
扩容结束,新的数组为:[1, 2, 3, 4, 5]
是否添加元素(y/n)?:
n
原数组不变:[1, 2, 3, 4, 5]
4-2.2.5 数组缩减:由用户自行决定删除哪个元素
类似于数组扩容,都是利用新数组来取代旧数组。本例要求删除数组中所有请求删除的元素,但要确保数组长度不为零(即至少保留一个元素)。
可先遍历原数组,获取待删除元素个数。计算新数组长度,若长度不为零,则再次通过遍历为新数组赋值;否则,直接新建一个长度为一,仅含待删除元素的数组。
本例所使用的数组为 int[] arr = {1,2,3,4,5,6,7,8,9,10};
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ArrayReduce {
public static void main(String[] args) {
//数组缩减:由用户选择删除那个元素,直至只剩下一个元素为止
//假设原始数组
int[] arr = {1,2,3,4,5,6,7,8,9,10};
System.out.println("原数组:" + Arrays.toString(arr));
String str = null;
int delInt = 0;
int counts = 0; //统计个数
Scanner scanner = new Scanner(System.in);
boolean flag = true; //外层循环
while (flag) {
System.out.println("请输入要删除的元素:");
//获取用户输入
try {
str = scanner.nextLine();
} catch (NoSuchElementException exception) {
System.out.println("非法输入,请重试。");
scanner = new Scanner(System.in);
System.gc();
continue;
} catch (Exception exception) {
System.out.println("出现异常,请重试。");
scanner = new Scanner(System.in);
System.gc();
continue;
}
//解析字符串为整型:使用包装类
try {
delInt = Integer.parseInt(str);
} catch (NumberFormatException exception) {
System.out.println("非法输入,请重试。");
continue;
} catch (Exception exception) {
System.out.println("出现异常,请重试。");
continue;
}
//查找元素
for (int i = 0; i < arr.length; i++) {
if (arr[i] == delInt) {
counts++;
}
}
//删除元素
int size = arr.length - counts;
//不允许新数组长度为零
if (size != 0) {
//新建数组
int[] newArr = new int[size];
//遍历
for (int i = 0, j = 0; i < newArr.length && j < arr.length;) {
if (arr[j] == delInt) {
j++;
continue;
} else {
newArr[i] = arr[j];
i++;
j++;
}
}
arr = newArr;
} else {
int[] newArr = {delInt}; //创建单一元素数组
arr = newArr;
}
counts = 0; //完成后清零。
System.out.println("新的数组为:" + Arrays.toString(arr));
do {
System.out.print("是否继续?(y/n):");
//获取用户输入
try {
str = scanner.nextLine();
} catch (NoSuchElementException exception) {
System.out.println("非法输入,请重试。");
scanner = new Scanner(System.in);
System.gc();
continue;
}
if (str.equals("Y") || str.equals("y")) {
break;
} else if (str.equals("N") || str.equals("n")) {
flag = false;
break;
} else {
System.out.println("非法输入,请重试。");
continue;
}
} while(true);
}
scanner.close();
}
}