我在创建连续数字数组的方法上遇到问题(即,如果您输入 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;
}
}
最佳答案
你的内部循环有问题。一旦从列表中删除一个元素,您就应该从该循环中中断。否则,您可能会删除不相关的附加号码(如果省略的数字在同一号码中出现多次)。
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--;
break; // add this
}
}
我用 1 到 50 的范围运行了你的代码(+我建议的修复)并省略了数字 4 并得到:
[1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 50]
代码中的问题发生在处理 44 时 - 在删除它之后(由于前 4 个,您继续 while 循环,找到另一个 4 并删除另一个数字,恰好是 39,因为数字 40 到 43 已被删除)。
关于java - 省略数字方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40283780/