【问题标题】:Reading String and Ints on the same file line在同一文件行上读取字符串和整数
【发布时间】:2021-12-21 19:15:13
【问题描述】:

您好,我有一个函数可以读取由空格分隔的 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

我有一个 Bet 类型类,我需要将名称保存为 String 以及该用户的下注向量中的其他元素。

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

我尝试了一些替代方法,但总是遇到 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();

【问题讨论】:

    标签: java arrays string vector parseint


    【解决方案1】:

    标记数组中的第一个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;
                }
            }
        }
    }
    

    【讨论】:

    • 完美我的朋友!祝贺你帮助社区和教学,用你的几行字我明白应该做什么。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2021-12-31
    相关资源
    最近更新 更多