读取文本文件时出现扫描仪不匹配异常

Scanner Mismatch Exception when reading text file

我的扫描仪正在使用分隔符读取文本文件。但是,当我 运行 程序唯一打印出的行是第一行数据时,我会抛出一个输入不匹配异常。我认为错误是它没有移到下一行。我了解不匹配的工作原理我只是不确定如何解决它。我试过把 scanner.nextLine();如您在下面的代码中所见。

这是我的扫描器代码:

 /**
 * Method for reading the data from the electricToolData.txt file.
 */
public void readElectricToolData()
{
  Frame myFrame = null; // initialises frame to null
  FileDialog fileBox = new FileDialog(myFrame,
                 "Open", FileDialog.LOAD);
  fileBox.setVisible(true);

  String directoryPath = fileBox.getDirectory();
  String filename = fileBox.getFile();

  System.out.println(filename + "   " + directoryPath); // prints out name of file and directory path


  try {
   File dataFile = new File(filename);
   Scanner scanner = new Scanner(dataFile);

   while(scanner.hasNext())
   {
       String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String

       //if statement checks if line starts with either "//" or space.
        if (lineOfText.startsWith("//") || lineOfText.isEmpty())
        { 

                      }
       else // now got real data
       {

        Scanner scanner2 = new Scanner(lineOfText);
        scanner2.useDelimiter(",");
        lineOfText.trim();
        System.out.println(lineOfText);


           while(scanner2.hasNext()) 
           {
          //lineOfText.trim();
          boolean mRechargeable = scanner.nextBoolean();
          String mPower = scanner.next();
          String mToolName = scanner.next();
          String mItemCode = scanner.next();
          int mTimesBorrowed = scanner.nextInt();
          boolean mOnLoan = scanner.nextBoolean();
          int mCost = scanner.nextInt();
          int mWeight = scanner.nextInt();
          scanner.nextLine();



          ElectricTool electricTool = new ElectricTool(mToolName, mItemCode, mTimesBorrowed, mCost, mWeight, mPower);
          toolsList.add(electricTool);

        }

       }





       //System.out.println(lineOfText); // prints out string
   }
   scanner.close();
   scanner.close(); // closes scanner


   }
       catch(FileNotFoundException e) 
  {
      System.err.println("Caught IOException: " + e.getMessage());
    }

  }   

错误显示在布尔值 mRechargeable = scanner.nextBoolean();.

这是数据文件:

// this is a comment, any lines that start with //
// (and blank lines) should be ignored

// data is rechargeable, power, toolName, itemCode, timesBorrowed, onLoan, cost, weight
true,18V,Makita BHP452RFWX,RD2001,12,false,14995,1800
true,10.8V,Flex Impact Screwdriver FIS439,RD2834,14,true,13499,1200     
false,1350W,DeWalt D23650-GB Circular Saw, RD6582,54,true,14997,5400
false,1500W,Milwaukee DD2-160XE Diamond Core Drill,RD4734,50,false,38894,9000
true,10.8V,Bosch GSR10.8-Li Drill Driver,RD3021,25,true,9995,820
 false,900W,Bosch GSB19-2REA Percussion Drill,RD8654,85,false,19999,4567
true,10.8V,Flex Impact Screwdriver FIS439, RD2835,14,false,13499,1200 
true,18V,DeWalt DW936 Circular Saw,RD4352,18,false,19999,3300 
false,2100W,Sparky FK652 Wall Chaser,RD7625,15,false,29994,8400

问题是 String.trim() 并不像您认为的那样工作:它不会改变调用它的字符串,而是 returns 一个有效地改变字符串的新字符串删除了白色space。这导致该行未被修剪,并且上面有很多 space 个字符的 "blank line" 然后无法通过您的第一个 scanner.nextBoolean() 调用进行解析。

所以,更新:

String lineOfText = scanner.nextLine(); // reads the next line of the file and stores as String

成为:

// read the next line of the file, removing enclosing whitespace
String lineOfText = scanner.nextLine().trim();

注释最好放在该行之前,因为它更易于阅读和格式化,而且更明显是一条注释。同时删除多余的 lineofText.trim();稍后在代码中。

此外,记得在完成后关闭所有 Scanner 实例(所以这里每行一个,文件一个)。

下一个问题是,在构建 ElectricTool 实例的内部循环中,您正在调用扫描仪上的方法,而不是 scanner2(将其重命名为更语义化的名称,例如 itemScanner):

Scanner itemScanner = new Scanner(lineOfText);
itemScanner.useDelimiter(",");

boolean mRechargeable = itemScanner.nextBoolean();
String mPower = itemScanner.next();
String mToolName = itemScanner.next();
String mItemCode = itemScanner.next();
int mTimesBorrowed = itemScanner.nextInt();
boolean mOnLoan = itemScanner.nextBoolean();
int mCost = itemScanner.nextInt();
int mWeight = itemScanner.nextInt();