测试区
public class zonghe {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
fangfa p=new fangfa();
int []a=new int[999999];
int chang=0;
boolean flag=true;
while (flag) {
p.notice();
int xuanze=sc.nextInt();
switch (xuanze) {
case 1:
System.out.println("请输入要初始化的值");
int size=sc.nextInt();
chang=size;
p.insertData(a, size);
break;
case 2:
p.showdata(a, chang);
break;
case 3:
System.out.println("请输入要插入的位置:");
int weizhi=sc.nextInt();
System.out.println("请输入要插入的数值:");
int shu=sc.nextInt();
chang=chang+1;
p.insertAtArray(a, weizhi, chang, shu);
break;
case 4:
p.divThree(a, chang);
break;
case 0:
flag=false;
System.out.println("推出成功");
break;
default:
System.out.println("请输入正确数字");
break;
}
}
}
}
方法区:
public class fangfa {
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("***************************");
System.out.println("请输入数字选择对应的操作:");
}
public void insertData(int[]a,int size) {
Scanner sc=new Scanner(System.in);
for (int i = 0; i <size; i++) {
System.out.println("请输入第"+(i+1)+"个值");
a[i]=sc.nextInt();
if (a[i]==0) {
System.out.println("0不能被输入");
i--;
}
}
System.out.println("数组元素为:");
for (int j = 0; j < size; j++) {
System.out.print(a[j]+" ");
}
System.out.println();
}
public void showdata(int[]a,int size) {
if (size<=0) {
System.out.println("还没有数据");
}
for (int i = 0; i < size; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
public void insertAtArray(int[]a,int weizhi,int chang, int zhi) {
if (weizhi<=0||weizhi>=chang) {
System.out.println("位置错误");
return;
}
if (zhi==0) {
System.out.println("0不能被输入");
return;
}
for (int i = chang-1; i >=weizhi-1; i--) {//-1的意思是变成索引
a[i+1]=a[i];
}
a[weizhi-1]=zhi;
for (int i = 0; i < chang; i++) {
System.out.print(a[i]+" ");
}
}
public void divThree(int[]a , int chang ) {
int count=0;
for (int i = 0; i <chang; i++) {
if (i%3==0) {
System.out.println(a[i]);
count++;
}
}
if (count==0) {
System.out.println("没有被3能整除的数");
}
}
}