1
我以一系列整數的形式捕獲用戶輸入,發生兩次,存儲在2個ArrayList中。這裏是我的代碼爲:當我試圖創建的list1
和list2
重複的做了一個list3
發生嵌套循環整數比較 - 意外索引
ArrayList<Integer> list1 = new ArrayList<Integer>();
System.out.println("Enter the first set of integers on one line, end with -1.");
Scanner scanner1 = new Scanner(System.in);
int item = 0;
while (
item != -1
) {
item = scanner1.nextInt();
list1.add(item);
}
//remove the last item on arraylist because its the -1
list1.remove(list1.size()-1);
//done making list1
//start list2
item = 0;
ArrayList<Integer> list2 = new ArrayList<Integer>();
System.out.println("Enter the first set of integers on one line, end with -1.");
Scanner scanner2 = new Scanner(System.in);
while (
item != -1
) {
item = scanner2.nextInt();
list2.add(item);
}
//remove the last item on arraylist because its the -1
list2.remove(list2.size()-1);
//end list2
我的問題。我通過將分別作爲(首先用於循環級別)從第一個列表中整數,並將其與第二個列表中的整數(來自循環嵌套的第二個)進行比較。 如果它們匹配,它們被添加到第三列表,這樣,
ArrayList<Integer> list3 = new ArrayList<Integer>();
for(int i=0;i<list1.size();i++){//list1
for(int j=0;j<list2.size();j++){//list2
if(list1.get(i) == list2.get(j)){//check if same
int value = list1.get(i);
list3.add(value);
}
}//for list 2
}//for list 1
說我跑的程序,提出了一些輸入,並打印清單變量:
[10, 200, 6, 99, 3, 5, 90, 44]
[200, 56, 34, 3, 5, 87, 44, 5]
這一切後,爲什麼list3
給我的印刷線聲明是:[3, 5, 5, 44]
爲什麼200忽略?我對索引不瞭解嗎?關於循環?還有別的嗎?