简体   繁体   English

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

[英]How do I read a certain string on a line from a file, using scanner?

I'm trying to read a text file which looks like this: 我正在尝试读取一个文本文件,如下所示:

A,32,0,0,0,0 A,32,0,0,0,0

And right now I have a static method which reads from that file. 现在,我有一个从该文件读取的静态方法。 I'm getting this NoSuchElement exception, while earlier I had a Mismatch exception. 我收到了这个NoSuchElement异常,而之前我有一个Mismatch异常。

May I ask what I'm missing in this code? 我可以问一下这段代码中我缺少什么吗? I'm sorry for the vagueness. 对不起,我很抱歉。

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;
 }

replace 更换

sc.nextLine()

with

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

By calling nextLine all your data for that line in your file is in exists . 通过调用nextLine,文件中该行的所有数据都exists

Take a look at the JavaDoc 看看JavaDoc

What do you need the exists-String for? 您需要存在字符串做什么?

Try: 尝试:

while (sc.hasNextLine()) {
   // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用扫描仪从命令行读取文件 - How can I read a file from the command line using scanner 如何使用扫描仪从同一行读取多个浮点数? - How do I read multiple floats from the same line with a scanner? 使用扫描仪和文本文件在一行中获取特定字符串 - Using scanner and a text file to get a certain string in a line 如何读取文件,以便对于包含特定字符串的每一行,将下面的行保存到 HashMap? - How do I read in a file such that for each line that contains a certain string, save the lines underneath to a HashMap? 使用扫描仪从文本文件中读取某一行 - Reading a certain line from a text file using Scanner 如何从扫描仪的单行输入中读取字符串和输入 - How to read String and input from a single line of input from scanner Java使用扫描程序读取文件然后读取行 - Java Using Scanner to Read File and Then Read Line Java扫描仪功能-如何从字符串内部抓取某些单词? - Java Scanner Function - How do I grab a certain word or words from inside a string? 如何使用扫描仪从键盘上读入一系列字符串,并将它们全部连接在一起 - How do I use Scanner to read in a series of Strings from the keyboard, all on one line, and concatenate them 如何让我的扫描仪读取文件中的下一行? - How can I get my scanner to read the next line in the file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM