该程序的一般功能是从txt文件中提取所有信息,将其输入到数组中,然后将用户输入的ID与输入到数组中的ID进行比较,并返回true或false。我写了程序,但是得到了InputMismatchException。将函数放在try / catch语句中时,运行该函数时将返回null。
这是我的验证器类:
import java.util.Scanner;
import java.io.*;
public class Validator
{
private int[] valid = new int[18];
public Validator(String filename) throws IOException
{
try
{
File file = new File(filename);
Scanner inputFile = new Scanner(file);
int index = 0;
while (inputFile.hasNext())
{
valid[index] = inputFile.nextInt();
index++;
}
inputFile.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public boolean isValid(int number)
{
int index = 0;
boolean found = false;
while (!found && index < valid.length)
{
if (valid[index] == number)
{
found = true;
}
index++;
}
return found;
}
}
至于主要方法:
import java.util.Scanner;
import java.io.*;
public class ChargeAccountModification
{
public static void main(String[] args) throws IOException
{
int number;
Scanner keyboard = new Scanner(System.in);
System.out.println("Brandon Woodruff 12/3/16");
System.out.print("Enter your charge account number: ");
number = keyboard.nextInt();
Validator validator = new Validator("AccountNumbers.txt");
if (validator.isValid(number) == true)
{
System.out.println("That's a valid account number.");
}
else
{
System.out.println("That's an INVALID account number.");
}
}
}
最后是txt信息。将该txt文件称为AccountNumbers.txt。
5658845
4520125
7895122
8777541
8451277
1302850
8080152
4562555
5552012
5050552
7825877
1250255
1005231
6545231
3852085
7576651
7881200
4581002
实际上,它们每个都出现在列表中各自的行上,但是我似乎无法使其显示出来。
最佳答案
在此代码中:
while (inputFile.hasNext()) {
valid[index] = inputFile.nextInt();
index++;
}
尝试用
hasNext()
替换hasNextInt()
: while (inputFile.hasNextInt()){
valid[index] = inputFile.nextInt();
index++;
}
否则,它将读取空白,并且空白不是数字。
如果不起作用,也可以使用带空格的定界符:
Scanner s = new Scanner(file).useDelimiter("\\s");