我有這個代碼要求用戶輸入數組大小(不能超過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