在同一文件行上读取 String 和 Ints

Reading String and Ints on the same file line

你好,我有一个函数可以读取由空格分隔的 int (0 1 0 2 0 1 0 2 0 1 0 1) 并逐个插入向量中的位置。 这工作正常。

    public void readTemplate() throws NumberFormatException, IOException {
    
    File templateFile = new File ("C:\Temp\templateFile.txt");
    FileReader fr = new FileReader(templateFile);
    BufferedReader br = new BufferedReader(fr);
    
    String row;
    
    int j=0;
    
    while((row = br.readLine()) != null) {
        String[] strings = row.split(" ");
        for (String str : strings) {
             Integer foo = Integer.parseInt(str);
             vectorTemplate[j] = foo;
             j++;
        }
            
            }
    br.close();
    fr.close();
    System.out.println("TEMPLATE FILE SUCCESFULY OPENED");
}

现在我有一个新的需求,就是在同一行读取一个字符串。

认为这是投注者的名字和他们的投注:

约翰 0 1 2 1 0 1 2 2 1 0 1 0

我有一个下注类型 class,我需要将名称保存为字符串,并将其他元素保存在该用户的下注向量中。

我不知道如何将第一个信息作为字符串读取以保存在我的变量名中,而该行的其余部分通常作为向量。

我尝试了一些替代方案,但我总是 运行 变成 java.lang.NumberFormatException

我认为错误出现在我用粗体显示的行中(totalBets[j].setName(str); )

public void betsReads() throws IllegalArgumentException, IOException {
    
    File betsFile = new File ("C:\Temp\bets.txt");
    FileReader fr = new FileReader(betsFile);
    BufferedReader br = new BufferedReader(fr);
    
    for(int j = 0; j < size; j++) { 
    
    String row;
      
    while((row= br.readLine()) != null) {
        totalBets[j] = new Bet();
        String[] strings = row.split(" ");
        for (String str : strings) {
            **totalBets[j].setName(str);**
            for(int i = 0; i < bets.vectorBets.length; i++) { 
             Integer foo = Integer.parseInt(str);
             totalBets[j].vectorBers[i] = foo;
            }
             j++;
        }
            
            }
            
            }
    br.close();
    fr.close();

令牌数组中的第一个 String 是名称。之后的每个值都是一个赌注。此外,使用 try-with-Resources 而不是显式关闭。喜欢,

public void betsReads() throws IllegalArgumentException, IOException {
    File betsFile = new File("C:\Temp\bets.txt");
    try (FileReader fr = new FileReader(betsFile);
                BufferedReader br = new BufferedReader(fr)) {
        String row;
        int j = 0;
        while ((row = br.readLine()) != null) {
            totalBets[j] = new Bet();
            String[] strings = row.split("\s+");
            totalBets[j].setName(strings[0]);
            for (int i = 1; i < strings.length; i++) {
                int foo = Integer.parseInt(strings[i]);
                totalBets[j].vectorBers[i - 1] = foo;
            }
        }
    }
}