正在开发一个 Java 程序,该程序读取带有一堆帐号的 txt 文件。用户输入帐号,如果匹配,则程序响应说它是有效的帐号,如果不匹配,则响应无效。这是我的类(class),它打开文件并检查它是否是有效的数字。当我运行代码时,即使我正在测试的帐号有效,它总是返回说帐号无效。
public class Validator {
public boolean isValid(int number) throws IOException {
final int SIZE = 17;
int[] numbers = new int[SIZE];
boolean found = false;
int index = 0;
File file = new File("src/Accounts.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext() && index < numbers.length) {
numbers[index] = inputFile.nextInt();
index++;
}
while (!found && index < SIZE) {
if (numbers[index] == (number))
found = true;
else
index++;
}
return found;
}
}
最佳答案
您应该在第二次循环之前将索引重置回 0。否则,将不会进入第二个循环,因为第一个循环已经将 index
递增到超过从文件读取的最后一个帐号的索引。
while (inputFile.hasNext() && index < numbers.length) {
numbers[index] = inputFile.nextInt();
index++;
}
index = 0; // add this
while (!found && index < SIZE) {
if (numbers[index] == (number))
found = true;
else
index++;
}
return found;
关于Java 输入和输出数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30062157/