java - 将文件中的数据存储到数组中

标签 java arrays

所以我有一个文本文件,其中的项目如下所示:

350279 1 11:54 107.15 
350280 3 11:55 81.27 
350281 2 11:57 82.11 
350282 0 11:58 92.43 
350283 3 11:59 86.11

我正在尝试根据这些值创建数组,其中每行的第一个值位于数组中,每行的第二个值位于数组中,依此类推。

这就是我现在拥有的所有代码,但我似乎不知道如何做到这一点。

package sales;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Sales {

    public static void main (String[] args) throws FileNotFoundException {

        Scanner reader = new Scanner(new File("sales.txt"));
        int[] transID = new int[reader.nextInt()];
        int[] transCode = new int[reader.nextInt()];
        String[] time = new String[reader.next()];
        double[] trasAmount = new double[reader.hasNextDouble()];


    }
}

最佳答案

以这种方式构建数组很困难,因为数组具有固定大小......您需要知道它们有多少个元素。如果您使用List,则不必担心提前知道元素的数量。试试这个(注意:这里没有错误检查!):

public static void main (String[] args) throws FileNotFoundException {
    Scanner reader = new Scanner(new File("sales.txt"));
    List<Integer> ids = new LinkedList<>();
    List<Integer> codes = new LinkedList<>();
    List<String> times = new LinkedList<>();
    List<Double> amounts = new LinkedList<>();

    // Load elements into Lists. Note: you can just use the lists if you want
    while(reader.hasNext()) {
        ids.add(reader.nextInt());
        codes.add(reader.nextInt());
        times.add(reader.next());
        amounts.add(reader.nextDouble());
    }

    // Create arrays
    int[] idArray = new int[ids.size()];
    int[] codesArray = new int[codes.size()];
    String[] timesArray = new String[times.size()];
    double[] amountsArray = new double[amounts.size()];        

    // Load elements into arrays
    int index = 0;
    for(Integer i : ids) {
        idArray[index++] = i;
    }
    index = 0;
    for(Integer i : codes) {
        codesArray[index++] = i;
    }
    index = 0;
    for(String i : times) {
        timesArray[index++] = i;
    }
    index = 0;
    for(Double i : ids) {
        amountsArray[index++] = i;
    }
}

关于java - 将文件中的数据存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16344101/

相关文章:

java - 如何在java中将消费者组添加到消息中?

用于远程 JAR 的 Java 注释处理器

java - 返回数组的所有负数元素

Java:带透明窗口的动画 GIF

java - 如何在 Java 中保存和加载数组

c++ - C++ 整数数组中的最小整数

javascript - 从数组中动态选择对象

java - 获取 ArrayIndexOutOfBoundsException,数组大小是动态确定的

java - NonUniqueObjectException session 不包含对象本身?

php - JS 数组转 PHP