今天學了Java的數組,寫了數組的插入和刪除,本人小白,寫給不會的小白看,大神請忽略,有錯請大家指出來;
/**
給數組指定位置數組的插入
*/
import java.util.*;
public class ArrayInsert{
public static void main(String []args){
System.out.println("請用鍵盤輸入5個數:");
int [] array =new int[10];
Scanner sc=new Scanner(System.in);
//通過鍵盤向數組輸入數
for(int i=0;i<array.length-5;i++){
array[i]=sc.nextInt();
}
//遍歷數組
System.out.print("原數組為:");
for(int a:array){
System.out.print(" "+a);
}
//向指定的位置插入數
System.out.println("\n請輸入插入位置:有效位置為0-----"+(array.length-1));
int index=sc.nextInt();
System.out.println("\n請輸入插入的值-----");
int num=sc.nextInt();
//調用靜態函數index
//遍歷插入后的數組
System.out.println("插入元素之后的數組遍歷:");
Insert(index,num,array);
for(int i=0;i<array.length;i++){
System.out.print(" "+array[i]);
}
}
//向數組指定位置插入數據方法
public static int[] Insert(int index,int num,int a[]){
//如果有元素,在索引之后的元素向后移一位,
for(int a[i]=a[i-1];
}
a[index]=num;
return a;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//刪除數組指定位置的數字。
import java.util.*;
public class ArrayDelete{
public static void main(String args[]){
System.out.println("請用鍵盤輸入5個數:");
int [] array =new int[10];
Scanner sc=new Scanner(System.in);
//通過鍵盤向數組輸入數
for(int i=0;i<array.length-5;i++){
array[i]=sc.nextInt();
}
//遍歷數組
System.out.print("原數組為:");
for(int a:array){
System.out.print(" "+a);
}
//刪除在指定位置的數字
System.out.println("\n輸入你要刪除的位置: 范圍在0---"+(array.length-1));
int index=sc.nextInt();
delete(index,array);//調用delete方法
//刪除之后的遍歷
System.out.println("刪除之后的遍歷:");
for(int i=0;i<array.length;i++){
System.out.print(" "+array[i]);
}
}
//數組的特性是,一旦初始化,則長度確定,所以要刪除數組中元素,並且長度也隨着刪除而改變,則要重新建立數組
/**
*刪除方式1
*/
public int[] delete(int index, int array[]) {
//數組的刪除其實就是覆蓋前一位
int[] arrNew = new int[array.length - 1];
for (int i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
System.arraycopy(array, 0, arrNew, 0, arrNew.length);
return arrNew;
}
/**
*刪除方式2
*/
public int[] delete2(int index, int array[]) {
//數組的刪除其實就是覆蓋前一位
int[] arrNew = new int[array.length - 1];
for (int i = 0; i < array.length - 1; i++) {
if (i < index) {
arrNew[i] = array[i];
} else {
arrNew[i] = array[i + 1];
}
}
return arrNew;
}
}
---------------------
作者:tangyaya8
來源:CSDN
原文:https://blog.csdn.net/tangyaya8/article/details/76595488/
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!