gpt4 book ai didi

java - 文件/扫描仪简单解析问题

转载 作者:行者123 更新时间:2023-12-02 07:30:30 24 4
gpt4 key购买 nike

给定一个文件和一个扫描仪对象,

File simpleFile = ranFi.getSelectedFile();
Scanner text = new Scanner(simpleFile);

还有这两个常见的说法:

    while(text.hasNext())
{
String currentLine = text.nextLine();

我尝试在单个 if 语句子句中使用 Scanner/String 类逻辑语句,该子句读取给定匹配正则表达式下的文件第一行,例如:

String fp100 = "[S][:][A-Ze0-1]";
String fp200 = "[S][:][A-Z0-1][A-Z0-1]";
//other regexes…

然后在同一 if 语句子句中调用适当的 Scanner/String 类方法来读取第二行和后续/可接受的行。我已经仔细阅读了 javadoc 但还没有弄清楚。使用 currentLine.matches(regex) 和 text.nextLine().matches(regex),编译此代码,

    if(currentLine.matches(fp100)||currentLine.matches(fp200)||
currentLine.matches(fp300) && text.nextLine().matches(fp100)||
text.nextLine().matches(fp101) || text.nextLine().matches(fp200)||
text.nextLine().matches(fp201) || text.nextLine().matches(fp300)||
text.nextLine().matches(fp301))
{

但立即抛出“无此类元素异常”。我究竟做错了什么?预先感谢您抽出时间。 编辑:我已经包含了堆栈跟踪,但删除了源代码,因为这是与项目相关的。

stack trace

最佳答案

我看到两个问题:

  1. 当您执行 if 条件时,text.nextLine() 可能不可用。

  2. 如果您的意思是说,当任何 currentLine 匹配 + 任何 nextLine 匹配为 true 时执行 if,然后将 || 参数括在大括号中,如下所示:

    if((currentLine.matches(fp100)||currentLine.matches(fp200)||
    currentLine.matches(fp300)) &&
    (text.nextLine().matches(fp100)||
    text.nextLine().matches(fp101) || text.nextLine().matches(fp200)||
    text.nextLine().matches(fp201) || text.nextLine().matches(fp300)||
    text.nextLine().matches(fp301)))

我想你想编写你的 while 循环,如下所示:

        while(text.hasNextLine()){
String currentLine = text.nextLine();
String nextLine = "";
if(text.hasNextLine())[
nextLine = text.nextLine();
}

/**ACC conditions*/
if((currentLine.matches(fp100)||currentLine.matches(fp200)
|| currentLine.matches(fp300))
&& (nextLine.matches(fp100)|| nextLine.matches(fp101)
|| nextLine.matches(fp200)
|| nextLine.matches(fp201) || nextLine.matches(fp300)
|| nextLine.matches(fp301)) {
//current line is OK
System.out.println(currentLine);
output.write(currentLine);
output.write("\n");
abc1List.add(currentLine);
lineOK++;

//next line is OK
System.out.println(nextLine);
output.write(nextLine);
output.write("\n");
abc1List.add(nextLine);
// <-- not sure if you want OK as 1 or 2 here
lineOK++;
} /**REJ conditions*/
else if(!currentLine.matches(fp100)||!currentLine.matches(fp101)||
!currentLine.matches(fp200)||!currentLine.matches(fp201)||
!currentLine.matches(fp300)||!currentLine.matches(fp301)){
System.out.println("invalid cfg; terminating....");
System.exit(0);
}
}//end of while

关于java - 文件/扫描仪简单解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12980407/

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