1:在数组中添加数据、删除数据、修改数据、返回指定位置的数据。

代码:

package text4;


 import java.util.Arrays;
 import java.util.Scanner;


 public class TextArray2 {


public static void main(String[] args) {
String[] num = { "12", "3", "56", "12", "45", null };
add(num, 2);
update(num, 2);
del(num, 2);
get(num, 2);
}


static void add(String[] str, int index) {
System.out.println("请输入插入的数据");
Scanner sc = new Scanner(System.in);
String newdate = sc.nextLine();
if (index < 0 || index > str.length) {
System.out.println("插入的位置不合法!!!");
} else {// 判断数组是否已满
if (str[str.length - 1] == null) {// 没满
int count = 0;
for (int i = str.length - 1; i > 0; i--) {// 找到数组中的最后一个数据的位置
if (str[i] != null) {
count = i;
break;
}
}
if (index > count) {// 插入的位置大于最后一个数据的位置
str[index] = newdate;
System.out.println("插入后的数组是:");
for (int j = 0; j < str.length; j++) {
System.out.print(str[j] + " ");
}
} else {
for (int j = count; j >= index; j--) {
str[j + 1] = str[j];
}
str[index] = newdate;
System.out.println("插入后的数组是:");
for (int j = 0; j < str.length; j++) {
System.out.print(str[j] + " ");
}
}
} else {// 满了
String[] newarr = Arrays.copyOf(str, str.length * 2);
for (int j = str.length - 1; j >= index; j--) {
newarr[j + 1] = newarr[j];
}
newarr[index] = newdate;
System.out.println("插入后的数组是:");
for (int j = 0; j < newarr.length; j++) {
System.out.print(newarr[j] + " ");
}
}


}


}


static void del(String[] str, int index) {
if (index < 0 || index >= str.length - 1) {
System.out.println("数据错误");
} else {
for (int i = index; i < str.length - 1; i++) {
str[i] = str[i + 1];
}
str[str.length - 1] = "";
System.out.println("\n删除后的数组是:");
for (int i = 0; i < str.length; i++) {
System.out.print(str[i] + " ");
}
}


}


static void update(String[] str, int index) {                 System.out.println("\n请输入更新的数据");
Scanner sc = new Scanner(System.in);
String newdate = sc.nextLine();
if (index < 0 || index >= str.length - 1) {
System.out.println("数据错误");
} else {
str[index] = newdate;
System.out.println("修改后的数组是:");
for (int i = 0; i < str.length; i++) {
System.out.print(str[i] + " ");
}
}


}


// 查询某个位置的元素
static void get(String[] str, int index) {
if (index < 0 || index >= str.length - 1) {
System.out.println("数据错误");
} else {
System.out.println("\n" + index + "位置的元素是:" + str[index]);
}


}


 }