我想验证客户端ID只有整数且不重复。 txt文件包含客户端详细信息,例如id,name等。 public void loadClientData(){
String fnm="", snm="", pcd="";
int num=0, id=1;
try {
Scanner scnr = new Scanner(new File("clients.txt"));
scnr.useDelimiter("\\s*#\\s*");
//fields delimited by '#' with optional leading and trailing spaces
while (scnr.hasNextInt()) {
id = scnr.nextInt();
snm = scnr.next();
fnm = scnr.next();
num = scnr.nextInt();
pcd = scnr.next();
//validate here type your own code
if( id != scnr.nextInt()) {
System.out.println("Invalid input! ");
scnr.next();
}
//some code...
}
}
}
它只会打印出第一个客户端。
任何帮助吗?
并且它已经过验证了吗?
这是client.txt
0001# Jones# Jack# 41# NX4 4XZ#
0002# McHugh# Hugh# 62# SS3 3DF#
0003# Wilson# Jonny# 10# LO4 4UP#
0004# Heath# Edward# 9# LO4 4UQ#
0005# Castle# Brian# 15# LO4 4UP#
0006# Barber# Tony# 11# LO4 4UQ#
0007# Nurg# Fred# 56# NE8 1ST#
0008# Nurg# Frieda# 56# NE8 1ST#
0009# Mouse# Mickey# 199# DD33 5XY#
0010# Quite-Contrary# Mary# 34# AB5 9XX#
答案 0 :(得分:1)
来自Scanner类的Java文档:
public int nextInt()
将输入的下一个标记扫描为int。
对nextInt()形式的此方法的调用完全相同 与调用nextInt(radix)的方式相同,其中radix是 此扫描仪的默认基数。
返回: 从输入扫描的int抛出:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range NoSuchElementException - if input is exhausted IllegalStateException - if this scanner is closed
如果扫描程序读取的是与InputMismatchException
正则表达式不匹配的无效输入,则该函数将抛出Integer
。
您可以使用try - catch
块来验证该异常并处理"错误"你想要的方式
您的代码中还有其他问题。我修改了它并将解释放在评论中
public static void loadClientData() {
try {
String fnm = "", snm = "", pcd = "";
int num = 0, id = 1;
Scanner scnr = new Scanner(new File("clients.txt"));
scnr.useDelimiter("\\s*#\\s*");
//fields delimited by '#' with optional leading and trailing spaces
//check for hasNext not hasNextInt since the next character might not be an integer
while (scnr.hasNext()) {
//here happens the integer validation
try {
id = scnr.nextInt();
} catch (InputMismatchException ex) {
System.out.println("Invalid input !");
}
System.out.print(id + " ");
snm = scnr.next();
System.out.print(snm + " ");
fnm = scnr.next();
System.out.print(fnm + " ");
num = scnr.nextInt();
System.out.print(num + " ");
pcd = scnr.next();
System.out.println(pcd + " ");
//you need to do this to get the scanner to jump to the next line
if (scnr.hasNextLine()) {
scnr.nextLine();
}
//validate here type your own code
/* if (id != scnr.nextInt()) {
System.out.println("Invalid input! ");
//scnr.next();
}*/
}
} catch (Exception ex) {
}
}