【问题标题】:Read lines from .txt and store into different integers从 .txt 读取行并存储到不同的整数中
【发布时间】:2016-02-29 18:54:41
【问题描述】:

所以我得到了以下代码:

    BufferedReader ind = new BufferedReader(new FileReader("Billet_priser.txt"));
    String line = ind.readLine();
    String[] bits = line.split(" "); // opdel i bidder efter mellemrum

    line = ind.readLine();
    bits = line.split(" ");
    Ticket1 = Integer.parseInt(bits[1]);
    line = ind.readLine();
    line.split(" ");
    Ticket2 = Integer.parseInt(bits[1]);
    line = ind.readLine();
    line.split(" ");
    ...
    line = ind.readLine();
    line.split(" ");
    Ticketn = Integer.parseInt(bits[1]);
}

使用以下文本从 .txt 文件中读取:

Ticket1 99
Ticket2 35
...
Ticketn 60

尝试获取每行空格后的第二位以存储在票整数中。

问题是它只将第一个读取的 int "99" 存储到所有票整数中。 我希望它在将第一个 int 存储到第一张票后读取下一行,然后读取下一行,依此类推。

【问题讨论】:

  • 你应该分割你读到的每一行,你也只分割第一行——看看如何使用循环

标签: java


【解决方案1】:

你继续使用这个bits 值来获取数字:

Ticket1 = Integer.parseInt(bits[1]);

但你只从第一行开始设置它一次

String[] bits = line.split(" ");     
while (line != null) {
    // bits is never updated in here
}

听起来你想简单地重复那行代码来更新bits变量:

line = ind.readLine();
bits = line.split(" ");
Ticket1 = Integer.parseInt(bits[1]);

(另请注意,您的循环没有多大意义,因为看起来您是在手动阅读每一行重复的代码,而不是实际循环。上面的三行代码,或者构成循环的一次迭代的任何内容,应该只存在一次。循环旨在一遍又一遍地重复该任务。)

【讨论】:

    【解决方案2】:

    您的实现有点偏离。你想制作一个票的容器并使用循环来填充它。

    List<Integer> tickets = new ArrayList<>();
    try (BufferedReader ind = new BufferedReader(new FileReader("Billet_priser.txt")){
        String line = null;
        while ((line = ind.readLine()) != null) {
            String[] bits = line.split(" ");     
            tickets.add(Integer.parseInt(bits[1]));
        }
    } 
    catch (IOException e) {
        e.printStackTrace();
    }
    

    【讨论】:

      【解决方案3】:

      您可能想要使用 Scanner 对象而不是 BufferedReader。像这样构造它:

      Scanner scannerObject = new Scanner(new File("Billet_priser.txt");
      

      然后修复您的 while 循环以执行类似这样的操作:

      while (scannerObject.hasNextLine()){
          String[] line = scannerObject.nextLine().split(" ");
          int currentTicket = Integer.parseInt(line[1]);
      }
      

      您还可以将票号存储在 ArrayList 中,如下所示:

      ArrayList<Integer> tickets = new ArrayList<>();
      

      那么您的 while 循环将如下所示:

      while (scannerObject.hasNextLine()){
          String[] line = scannerObject.nextLine().split(" ");
          tickets.add(Integer.parseInt(line[1]));
      }
      

      【讨论】:

        猜你喜欢
        • 2012-11-22
        • 1970-01-01
        • 1970-01-01
        • 2013-06-03
        • 1970-01-01
        • 2012-08-20
        • 1970-01-01
        • 1970-01-01
        • 2015-01-22
        相关资源
        最近更新 更多