标签:break util 元素 索引 添加元素 tar index public 插入
1.查询元素
import java.util.Arrays; import java.util.Scanner; public class TestArry2 { public static void main(String[] args) { //数组查询 int arr[] = new int[]{12, 34, 55, 11, 151}; System.out.println(Arrays.toString(arr)); System.out.println("输入要查找的数"); Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); int index = query(arr, num); if (index > 0) { System.out.println("索引为" + index); } else { System.out.println("查无次数"); } } public static int query(int arr[], int num) { int index = -1; for (int i = 0; i <= arr.length - 1; i++) { if (arr[i] == num) { index = i; break; } } return index; } }
2.添加元素
import java.util.Arrays; import java.util.Scanner; public class TestArry3 { public static void main(String[] args){ //添加元素 int arr[]=new int[]{12,43,65,77,11}; System.out.println(Arrays.toString(arr)); Scanner scanner=new Scanner(System.in); System.out.println("输入要添加的元素"); int num=scanner.nextInt(); System.out.println("输入要插入的索引位置"); int n=scanner.nextInt(); add(arr,n,num); System.out.println(Arrays.toString(arr)); } public static void add(int arr[],int n,int num){ for (int i=arr.length-1;i>=(n+1);i--){ arr[i]=arr[i-1]; } arr[n]=num; } }
3.删除元素
import java.util.Arrays; import java.util.Scanner; public class TestArry4 { public static void main(String[] args) { //删除元素 int arr[] = new int[]{12, 34, 56, 77, 100}; System.out.println(Arrays.toString(arr)); Scanner scanner = new Scanner(System.in); System.out.println("输入要删除的元素"); int num = scanner.nextInt(); int index = query(arr, num); delete(arr, index); System.out.println(Arrays.toString(arr)); } //查找索引 public static int query(int arr[], int num) { int index = -1; for (int i = 0; i <= arr.length - 1; i++) { if (arr[i] == num) { index = i; break; } } return index; } //删除元素 public static void delete(int arr[], int index) { for (int i = index; i <= arr.length - 2; i++) { arr[i] = arr[i + 1]; } arr[arr.length - 1] = 0; } }
标签:break util 元素 索引 添加元素 tar index public 插入
原文地址:https://www.cnblogs.com/zimo-bwl1029-s/p/11266565.html