代码略显粗糙
有可优化的地方可以留言指教,不胜感激
数组缩减,每次缩减最后的数字(仅剩一个数字的情况下不进行缩减)
import java.util.Scanner;
public class array2{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//定义初始数组
int[] array1 = {5,4,3,2,1};
System.out.println("array number ");//打印
for (int i = 0;i < array1.length ;i++) {
System.out.print(array1[i] + "\t");
}
//选择是否删除尾部数字
do{
System.out.println();
System.out.println("do you delete the last number? y/n");
char answer = input.next().charAt(0);
if(answer == 'y'){
if(array1.length == 1){ //在只剩下一个数字的时候停止删除
break;
}else{
int[] array2 = new int[array1.length - 1];
for(int j = 0;j < array2.length; j++){
array2[j] = array1[j];
}
array1 = array2;
}
}else{
break;
}
//打印删除过后的数组
System.out.println("array number ");
for (int i = 0;i < array1.length ;i++) {
System.out.print(array1[i] + "\t");
}
}while(true);
}
}
数组指定数字进行删除,并缩减为小一号的数组(仅剩一个数字的情况下不进行删除)
import java.util.Scanner;
public class arraydelete{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//定义初始数组
int[] array1 = {5,4,3,2,1};
int indexnumber = -1;
System.out.println("array number ");//打印
for (int i = 0;i < array1.length ;i++) {
System.out.print(array1[i] + "\t");
}
//选择是否删除尾部数字
do{
System.out.println();
System.out.println("do you delete the number? y/n");
char answer = input.next().charAt(0);
if(answer == 'y'){
if(array1.length == 1){ //在只剩下一个数字的时候停止删除
break;
}else{
//输入想要删除的数字
System.out.println("enter the number you want to delete");
int number = input.nextInt();
for(int x = 0;x < array1.length; x++){
if(array1[x] == number){
indexnumber = x;
int[] array2 = new int[array1.length - 1];
for(int j = 0;j < array2.length; j++){
if(j >= x){
array2[j] = array1[j+1];
}else{
array2[j] = array1[j];
}
}
array1 = array2;
}
}
}
}else{
break;
}
//打印删除过后的数组
System.out.println("array number ");
for (int i = 0;i < array1.length ;i++) {
System.out.print(array1[i] + "\t");
}
}while(true);
//当输入的数字没有时
if(indexnumber == -1){
System.out.println("there is no number that you enter");
}
}
}