Input Mismatch Exception Error,

时间:2015-12-10 01:04:59

标签: java java.util.scanner

Program compiles and runs perfectly until I try to execute my load method in main. Program crashes and gives me an input mismatch exception at part number = scan.nextInt(); ..... Anyone know why?

public static InventoryManager load(String fileName) throws IOException,ClassNotFoundException
{
    Scanner fileScan = new Scanner (new File(fileName));
    Scanner stringScan;
    InventoryManager StockChart = new InventoryManager();

   // Part variables
   String record = "";
   int partNumber=0;
   String description="";
   int qty=0; 
   double cost = 0.00; 


  while(fileScan.hasNext())
  {
     record = fileScan.nextLine();
     stringScan = new Scanner (record);
     stringScan.useDelimiter("  ");     //allows for separation when reading 
     partNumber = stringScan.nextInt(); // scans part number
     description = stringScan.next();   // scans description 
     qty = stringScan.nextInt();        // scans the qty on hand 
     cost = stringScan.nextDouble();    // scans the item cost 

     //create new part object for each line in file 
     StockChart.addStock(new Stock(partNumber,description, qty,cost)); 

  }


    return StockChart; // return new list back to InventoryClerk program 
}

Text File is formatted as follows (disregard spaces in between):

1117[tab]1/2-13 FHN[tab]450[tab]6.11

1118[tab]1/2-13 FHN[tab]100[tab]0.23

1119[tab]1/2-13 FHN[tab]100[tab]4.11

1 个答案:

答案 0 :(得分:2)

A better way rather than using the stringScan Scanner object is to simply to use String.split on the record String

e.g.

while(fileScan.hasNext())
{
   record = fileScan.nextLine();
   String el[] = record.split (" ");
   partNumber = Integer.parseInt (el[0]);
   description = el[1];
   // etc