首页 > 应用开发 > Java > Java 数组 之 一维数组 删除 元素
转载于 : http://www.verejava.com/?id=16992656053526
/**
题目: 删除scores数组索引index位置的值
思路:
1. 创建一个临时比scores 小1的临时数组tempArray
2. 将index前面的数据复制到tempArray前面
3. 将index后面的数组依次复制到 tempArray 后面
4. 将tempArray地址指针引用赋值给 scores
5. 打印输出scores
*/import java.util.Scanner;public class ArrayDelete {
public static void main(String[] args) { //一维数组的定义和初始化
int[] scores = { 90, 70, 50, 80, 60, 85 };
System.out.println("请输入要删除的索引index :");
Scanner in = new Scanner(System.in); int index = in.nextInt(); //1. 创建一个临时比scores 小1的临时数组tempArray
int[] tempArray = new int[scores.length - 1]; //2. 将index前面的数据复制到tempArray前面
//3. 将index后面的数组依次复制到 tempArray 后面
for (int i = 0; i < scores.length; i++) { if (i < index)
tempArray[i] = scores[i]; if (i > index)
tempArray[i - 1] = scores[i];
} //4. 将tempArray地址指针引用赋值给 scores
scores = tempArray; //5.打印输出scores
for (int i = 0; i < scores.length; i++) {
System.out.print(scores[i] + ",");
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10054744/viewspace-2199985/ ,如需转载,请注明出处,否则将追究法律责任。