我有这个代码要求用户输入数组大小(不能超过50),并且数组大小已成功设置为数组。告诉用户输入的号码是否已经存储在阵列中
我的问题是在第二段代码。 基本上,我希望它存储由用户输入的数字(哪些工作),但是,如果数字已经给予数组,则告知用户该数字已经被添加并且数字不被存储。例如:用户输入1,4,6,1。当再次给出1时,程序应该告诉用户数字1已经存储在数组中。
我能做些什么,以使程序(使用的ArrayList我可以使用。载,但阵列不具备这一点,似乎)
public static void main(String[] args) {
Scanner reader = new Scanner (System.in);
int[] listA;
while (true) {
System.out.println("Enter array size for listA: ");
int listAsize = Integer.parseInt(reader.nextLine());
if (listAsize > 50) {
System.out.println("Array size must not exceed 50!");
} else {
listA = new int [listAsize];
//System.out.println(listA.length);
break;
}
}
int counter = 0;
while (counter < listA.length) {
System.out.print("Enter number to add to listA: ");
int inputListA = Integer.parseInt(reader.nextLine());
**if (listA.equals(listA[counter])) {**
System.out.println(inputListA + " was already added to the array, enter a different number");
} else {
listA[counter] = inputListA;
counter++;
}
}
保持一个ArrayList的,而不是数组? – smk