我正在做一个过去的CCC(加拿大计算竞赛)问题,我得到了一个奇怪的错误,当我将indexOf()用于ArrayList中的整数时,它返回0。
以下是代码:
package problem4;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
public class Problem4 {
static List<Integer> totalnum = new CopyOnWriteArrayList<>();
static ArrayList<Integer> div = new ArrayList<>();
static String output = "";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
try {
int total = in.nextInt();
for (int i = 0; i < total; i++) {
totalnum.add(i + 1);
}
int roundnum = in.nextInt();
for (int i = 0; i < roundnum; i++) {
int tempnum = in.nextInt();
div.add(tempnum);
}
print("cache org: " + totalnum.toString());
for (int divnum : div) {
for (int check : totalnum) {
print(check + " index: " + totalnum.indexOf(check));
if (totalnum.indexOf(check) % divnum == 0) {
totalnum.remove(totalnum.indexOf(check));
}
}
print("cache " + divnum + ": " + totalnum.toString());
}
String output = totalnum.toString().replace("[", "")
.replace("]", "").replace(",", "");
for (int i = 0; i < output.length(); i++) {
System.out.println(output.charAt(i));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void print(String input) {
System.out.println(input);
}
}
这是输入/输出:
10
2
2
3
cache org: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1 index: 0
2 index: 0
3 index: 0
4 index: 0
5 index: 0
6 index: 0
7 index: 0
8 index: 0
9 index: 0
10 index: 0
cache 2: []
cache 3: []
任何人都知道出了什么问题?
答案 0 :(得分:1)
在每次迭代后删除第一个元素,以便下一个元素成为第一个元素。只需在每次迭代后打印数组内容:
for (int divnum : div) {
for (int check : totalnum) {
print(check + " index: " + totalnum.indexOf(check));
if (totalnum.indexOf(check) % divnum == 0) {
totalnum.remove(totalnum.indexOf(check));
}
print("cache " + divnum + ": " + totalnum.toString());
}
print("cache " + divnum + ": " + totalnum.toString());
}
然后,对于您的输入,您将看到此类输出
cache org: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1 index: 0
cache org: [2, 3, 4, 5, 6, 7, 8, 9, 10]
2 index: 0
cache org: [3, 4, 5, 6, 7, 8, 9, 10]
3 index: 0
cache org: [4, 5, 6, 7, 8, 9, 10]
4 index: 0
cache org: [5, 6, 7, 8, 9, 10]
5 index: 0
cache org: [6, 7, 8, 9, 10]
6 index: 0
cache org: [7, 8, 9, 10]
7 index: 0
cache org: [8, 9, 10]
8 index: 0
cache org: [9, 10]
9 index: 0
cache org: [10]
10 index: 0
cache org: []
cache 2: []
cache 3: []