如何使用扫描仪从文件中读取某一行中的某个字符串?

时间:2013-04-24 08:42:41

标签: java string delimiter comma

我正在尝试阅读一个看起来像这样的文本文件:

A,32,0,0,0,0

现在我有一个从该文件中读取的静态方法。我得到了这个NoSuchElement异常,而早些时候我遇到了Mismatch异常。

请问这段代码中我缺少什么?我很抱歉模糊不清。

public static ArrayList<RaceCar> readCar(String s, Track raceTrack)throws IOException,FileNotFoundException
 {
     Scanner sc = new Scanner(new File("CarData.txt"));
     sc.useDelimiter(",");
     String exists;
     ArrayList<RaceCar> racers = new  ArrayList<RaceCar>();

    while ((exists = sc.nextLine()) != null) 
    {
         String dName = sc.next();
         int dNum = sc.nextInt();
         int dWins = sc.nextInt();
         int dRunUp = sc.nextInt();
         int dRaces = sc.nextInt();

         racers.add(new RaceCar(dName,dNum,raceTrack,dWins,dRunUp,dRaces));
    }   

    return racers;
 }

2 个答案:

答案 0 :(得分:1)

替换

sc.nextLine()

while (sc.hasNext()) {
  //code
} 

通过调用nextLine,您文件中该行的所有数据都在exists

查看JavaDoc

答案 1 :(得分:0)

你需要什么 - 字符串?

尝试:

while (sc.hasNextLine()) {
   // ...
}
相关问题