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忽略?我对索引不了解吗?关于循环?还有别的吗?