設計一個類,用於數組操作
(1)成員變量爲一個一位數組,數組爲int型
(2)構造方法中包含一維數組
(2)成員方法中包括數組遍歷 添加 刪除 。。。
import
java.util.Scanner;
/*
許昌學院
馬志勇
互助
互祝
互祝
*/
package 三個題3_18;
import java.sql.Array;
import
java.util.Scanner;
class ArrayTool {
int arr[];
public ArrayTool() {
}
public ArrayTool(int a[]) {
this.arr = a;
}
// 添加元素
public void append() {
System.out.print("當前數組各元素爲:");
display();
System.out.print("你想添加序號爲多少的元素:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print("數字爲:");
int count = sc.nextInt();
//
=========================================
int[] newArray = new int[arr.length + 1];
for (int i = 0; i < arr.length+1; i++) {
if (i < n-1) {
newArray[i] = arr[i];
} else if(i==n-1){
newArray[i]=count;
}else{
newArray[i]=arr[i-1];
}
}
arr = newArray;
System.out.print("添加後的數組爲爲:");
display();
// ========================================
}
// 遍歷元素
public void display() {
for (int i = 0; i < arr.length; i++) {
if (i < arr.length - 1) {
System.out.print(arr[i] + ",");
} else {
System.out.println(arr[i] + "。");
}
}
}
// 刪除元素
public void remove() {
System.out.print("當前數組各元素爲:");
display();
System.out.print("你想刪除第幾個元素:");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//
=========================================
int[] newArray = new int[arr.length - 1];
for (int i = 0; i < newArray.length; i++) {
if (i < n - 1) {
newArray[i] = arr[i];
} else {
newArray[i] = arr[i + 1];
}
}
arr = newArray;
System.out.print("刪除後的元素爲:");
display();
}
// 查找元素
public int indexof(int n) {
int t = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == n) {
t++;
t = i + 1;
}
}
return t;
}
// 排序元素
public void sort(String shunxu) {// 既可以逆序 又可以順序
if (shunxu == "順序") {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
int mid;
if (arr[i] > arr[j]) {
mid = arr[j];
arr[j] = arr[i];
arr[i] = mid;
}
}
}
System.out.print("順序後結果爲:");
display();
} else {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
int mid;
if (arr[i] < arr[j]) {
mid = arr[j];
arr[j] = arr[i];
arr[i] = mid;
}
}
}
System.out.print("逆序後結果爲:");
display();
}
}
}
public class ArrayTest {
public static void main(String[] args) {
System.out.println("-------------遍歷 刪除展示------------------");
// 定義一個數組實現 :遍歷 刪除
int aa[] = { 1, 3, 7, 5, 9 };
ArrayTool a = new ArrayTool(aa);
// 遍歷
System.out.print("遍歷:");
a.display();
// 刪除
System.out.println("開始啓動刪除程序...................");
a.remove();
System.out.println("----------------------");
// 再定義一個數組實現 : 查找 排序
System.out.println("-------------查找 排序 展示------------------");
// 查找展示
int bb[] = { 1, 6, 3, 8, 4, 9 };
ArrayTool b = new ArrayTool(bb);
int xuhao = b.indexof(9);
System.out.println("你要查的元素在:" + xuhao);
int xuhao2 = b.indexof(1999);
System.out.println("你要查的元素在:" + xuhao2);
// 排序展示
b.sort("逆序"); // 逆序排
b.sort("順序"); // 順序
System.out.println("-------------添加元素展示------------------");
int add[]={1,4,3,6};
ArrayTool at=new ArrayTool(add);
at.append();
}
}