【发布时间】:2017-03-10 02:08:06
【问题描述】:
我在创建连续数字数组的方法时遇到问题(即,如果您输入 1 和 10 作为参数,该数组将包含 1-10 中的每个数字),然后将每个数字与另一个数字进行比较数字(例如 4) - 如果数字匹配(例如 4 == 4),则从数组中删除该数字。最后它返回那个数组。
我已经实现了下面的方法,它有时有效,但不是一直有效,我不知道为什么?
例如,如果我创建了一个新数组并打印了每个数组:
ArrayList<Integer> omittedDigitArray = new ArrayList<Integer>(Omit.allIntegersWithout(20, 45, 3));
System.out.println("Array - Numbers with Omitted Digit:");
for (int n : omittedDigitArray) {
System.out.print(n + ", ");
}
数组中省略了数字 29?谁能告诉我为什么?谢谢!
// Creates the ArrayList
ArrayList<Integer> numberList = new ArrayList<Integer>();
// Loop creates an array of numbers starting at "from" ending at "to"
for (int i = from; i < to + 1; i++) {
numberList.add(i);
}
// Check the array to see whether number contains digit
// Code checks whether x contains 5, n == one digit
// IMPORTANT: Doesn't work on the first half of numbers i.e / will remove 3 but not 30
for (int j = 0; j < numberList.size(); j++) {
int number = (int) numberList.get(j); // This can be any integer
int thisNumber = number >= 0 ? number: -number; // if statement in case argument is negative
int thisDigit;
while (thisNumber != 0) {
thisDigit = thisNumber % 10; // Always equal to the last digit of thisNumber
thisNumber = thisNumber / 10; // Always equal to thisNumber with the last digit chopped off, or 0 if thisNumber is less than 10
if (thisDigit == omittedDigit) {
numberList.remove(j);
j--;
}
}
}
// Return the completed Array list
return numberList;
}
}
【问题讨论】:
-
当您从列表中删除项目时,您应该向后遍历列表。这样,您不必调整列表索引计数器。此外,您的说明没有说明数字是否在数字中。您的说明会说明数字是否匹配。
标签: java arrays while-loop