gpt4 book ai didi

java - 如何在java中验证txt扫描仪数据

转载 作者:行者123 更新时间:2023-12-01 09:14:16 24 4
gpt4 key购买 nike

我想验证客户端 ID 是否只有整数且不重复。txt 文件包含客户详细信息,例如 ID、名称等。 公共(public)无效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#

最佳答案

来自 Scanner 类的 Java 文档:

public int nextInt()

Scans the next token of the input as an int.

An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

Returns: the int scanned from the input Throws:

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

如果扫描器读取到与 Integer 正则表达式不匹配的无效输入,该函数将抛出 InputMismatchException

您可以使用 try - catch block 使用该异常进行验证,并按照您想要的方式处理“错误”

您的代码中还存在其他问题。我修改了一下,并将说明放在评论中

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) {

}

}

关于java - 如何在java中验证txt扫描仪数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com