一.有一个数组,键盘输入一个下标,获取指定下标位置的数字
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int [] arr = new int[]{4,58,69,14,22,-1};
System.out.println("请输入一个下标:");
int index = sc.nextInt();
if(index >= 0 && index <= arr.length - 1){
// 合法的情况
System.out.println("对应位置的值是:" + arr[index]);
} else {
System.out.println("你输入的数据有误,无法获取...");
二.在数组中倒序输入数字
Scanner sc = new Scanner(System.in);
int [] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
System.out.println("请输入第" + (i+1) +"个数:");
// 输入
int num = sc.nextInt();
arr[arr.length - 1 - i] = num;
}
for (int i : arr) {
System.out.println(i);
}
三.在数组中倒叙输入数字的情况下,进行扩容
Scanner sc = new Scanner(System.in);
int [] arr = new int[2];
int i = 0;
main:while(true){
System.out.println("请输入数据:");
int num = sc.nextInt();
arr[arr.length - 1 - i] = num;
i++;
if(i >= arr.length) {
int [] newArr = new int[arr.length * 2];
for (int j = 0; j < arr.length; j++) {
newArr[newArr.length - 1 - j] = arr[arr.length - 1 - j];
}
arr = newArr;
}
System.out.println("是否继续添加:1、是 2、否");
String flag = sc.next();
switch (flag){
case "1":
continue;
case "2":
System.out.println("当前数组为:" + Arrays.toString(arr));
break main;
// System.exit(-1);
}
四.在数组指定位置中倒叙输入数字并且进行扩容
Scanner sc = new Scanner(System.in);
int [] arr = new int[]{1,2,3,4,5};
// 扩容
int [] newArr = new int[arr.length * 2];
for (int j = 0; j < arr.length; j++) {
newArr[j] = arr[j];
}
arr = newArr;
main:while(true){
System.out.println("请输入要插入数据的下标:");
int index = sc.nextInt();
System.out.println("请输入要插入的数据:");
int num = sc.nextInt();
int temp = arr[index];
arr[index] = num;
for (int i = 1; i < arr.length - index; i++) {
arr[arr.length - i] = arr[arr.length - 1 - i];
}
arr[index + 1] = temp;
System.out.println("现在数组为:" + Arrays.toString(arr));
System.out.println("是否继续添加:1、是 2、否");
String flag = sc.next();
switch (flag){
case "1":
continue;
case "2":
System.out.println("当前数组为:" + Arrays.toString(arr));
break main;
// System.exit(-1);
原创文章,作者:jamestackk,如若转载,请注明出处:https://blog.ytso.com/275077.html