java 简单数组元素的增删改查

public class Test {

static int[] a = new int[20];

static int n;

public static void main(String[] args) {

int choose;

Scanner sc = new Scanner(System.in);

	System.out.println("请输入初始时存放元素的个数");
n = sc.nextInt(); System.out.println("请输入元素");
for(int i=0; i<n; i++){
a[i] = sc.nextInt();
} notice(); while(true){
switch(choose = sc.nextInt()){
case 0:
System.out.println("程序已退出,如需操作请重新运行");
System.exit(0);
break;
case 1:
System.out.println("你所遍历的元素列表");
traversal();
break;
case 2:
insertElement();
traversal();
break;
case 3:
deleteElement();
traversal();
break;
case 4:
updateElement();
traversal();
break;
default:
System.out.println("你输入错误,请重新输入");
}
}
} private static void updateElement() {
int position, elements; Scanner sc = new Scanner(System.in);
System.out.println("请输出要修改元素的位置");
position = sc.nextInt();
System.out.println("请输出修改后的元素");
elements = sc.nextInt(); a[position-1] = elements;
} private static void deleteElement() {
int position; Scanner sc = new Scanner(System.in);
System.out.println("请输入元素删除的位置");
position = sc.nextInt(); for(int i=position-1; i<n; i++)
a[i] = a[i+1];
} private static void insertElement() {
int position, elements; Scanner sc = new Scanner(System.in);
System.out.println("请插入元素的位置");
position = sc.nextInt();
System.out.println("请插入该位置的元素");
elements = sc.nextInt(); for(int i=n-1; i>=position-1; i--)
a[i+1] = a[i];
a[position-1] = elements;
} private static void traversal() {
for(int i=0; i<n; i++)
System.out.print(a[i]+" ");
System.out.println("\n");
notice();
} private static void notice() {
System.out.println("0.退出操作. \n1.遍历元素. \n2.插入元素. \n3.删除元素。 \n4.修改元素.");
}

}

BF078ECBF2D1F6D52452666367378573

上一篇:关于zipfile解压出现的字符编码问题


下一篇:struts2重点——ValueStack和OGNL