使用java程序读取带有一堆帐号的txt文件。用户输入帐号,如果它与程序响应相匹配,说明它是一个有效的帐号,如果它不是,它的响应无效。这里是我的类,它打开文件并检查它是否是一个有效的数字。当我运行代码时,它总是返回,说帐号无效,尽管我正在测试的帐号是有效的。
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;
}
}发布于 2015-05-05 20:02:35
您应该在第二个循环之前将索引重置为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;发布于 2015-05-05 20:11:02
我已经简化了你的代码。您可以同时查看文件和检查。
public boolean isValid(int number) {
try (Scanner scanner = new Scanner(new File("src/Accounts.txt"))) {
while (scanner.hasNextInt()) {
if (scanner.nextInt() == number) {
return true;
}
}
}
return false;
}发布于 2015-05-05 20:31:04
我也简化了您的代码,但是在您的帐号参数类型中发现了一个可能的问题。你的帐户能大于"2,147,483,647“吗?(datatypes.htm)
如果答案是肯定的,那么你就会有问题。
简化代码如下:
public boolean isValid(long number) {
long accountNumber;
File file = new File("src/Accounts.txt");
Scanner inputFile = null;
try {
inputFile = new Scanner(file);
while (inputFile.hasNext()) {
accountNumber = inputFile.nextLong();
if (accountNumber == number) {
return true;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputFile != null) {
inputFile.close();
}
}
return false;
}https://stackoverflow.com/questions/30062157
复制相似问题