public class Demo {
public int[] insertData(){
int[] a = new int[10];
Scanner sc = new Scanner(System.in);
for(int i = 0; i < a.length - 1; i++){
System.out.println("输入第" + (i + 1) + "数");
try{
a[i] = sc.nextInt();
} catch(InputMismatchException e){
System.out.println("输入有误,不能是非数字,请重新输入");
sc.next();
i--;
}
}
return a;
}
public void showData(int[] a, int length){
for(int i = 0; i < length; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
}
public void inserAtArray(int[] a,int n,int k) {
for(int i = a.length - 1; i > k; i--) {
a[i] = a[i-1];
}
a[k] = n;
}
public void divThree(int[] a) {
String str = " ";
int count = 0;
for(int n : a) {
if(n % 3 == 0) {
str = str + n +" ";
count++;
}
}
if(count == 0) {
System.out.println("数组中没有能被3整除的数据");
} else {
System.out.println("数组中能被3整除的数据为:" + str);
}
}
public void notice(){
System.out.println("**********************");
System.out.println(" 1 --插入数据");
System.out.println(" 2 --显示所用数据");
System.out.println(" 3 --在指定位置插入数据");
System.out.println(" 4 --查询能被3整除的数据");
System.out.println(" 0 --退出");
System.out.println("**********************");
}
public static void main(String[] args){
Demo demo = new Demo();
Scanner sc = new Scanner(System.in);
int input;
int[] a = null;
int n = 0;
int k = 0;
while(true) {
demo.notice();
System.out.println("请输入对应的数字进行操作!");
try{
input = sc.nextInt();
} catch(InputMismatchException e){
System.out.println("输入有误,不能是非数字,请重新输入!");
sc.next();
continue;
}
if(input == 0) {
System.out.println("退出程序");
break;
}
switch(input) {
case 1: {
a = demo.insertData();
System.out.println("数组元素为:");
demo.showData(a, a.length - 1);
break;
}
case 2: {
if(a != null) {
System.out.println("数组元素为:");
if(a[a.length - 1] == 0) {
demo.showData(a, a.length - 1);
} else {
demo.showData(a, a.length);
}
} else {
System.out.println("还没有在数组中插入数据!");
}
break;
}
case 3: {
if(a != null) {
System.out.println("请输入要插入数据:");
try {
n = sc.nextInt();
System.out.println("请输入要插入数据的位置:");
k = sc.nextInt();
} catch(InputMismatchException e) {
System.out.println("输入有误,不能是非数字,请重新输入!");
sc.next();
break;
}
demo.inserAtArray(a, n, k);
demo.showData(a, a.length);
} else {
System.out.println("还没有在数组中插入数据!");
}
break;
}
case 4: {
if(a != null) {
System.out.println("能被3整除的数为:");
demo.divThree(a);
} else {
System.out.println("还没有在数组中插入数据!");
}
break;
}
default: {
System.out.println("请输入对应的数字进行操作");
}
}
}
}
}