簡體   English   中英

將數據從文件存儲到數組中

[英]Storing Data from File into an Array

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

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

使用數組列表,因為數組具有固定大小,並使用Arraylist動態添加元素

   Scanner reader = new Scanner(new File("test.txt"));
    List<Integer> transID = new ArrayList<Integer>();
    List<Integer> transCode = new ArrayList<Integer>();
    List<String> time= new ArrayList<String>();
    List<Double> trasAmount = new ArrayList<Double>();

    while(reader.hasNext() )
    {
        transID.add(reader.nextInt());
        transCode.add(reader.nextInt());
        time.add(reader.next());
        trasAmount.add(reader.nextDouble());

    }

    System.out.println(transID.toString());
    System.out.println(transCode.toString());
    System.out.println(time.toString());
    System.out.println(trasAmount.toString());

輸出上面的代碼

transID     [350279, 350280, 350281, 350282, 350283]
transCode   [1, 3, 2, 0, 3]
time        [11:54, 11:55, 11:57, 11:58, 11:59]
trasAmount  [107.15, 81.27, 82.11, 92.43, 86.11]

你需要一個while循環來檢查輸入。 由於並非所有輸入都是整數,因此您可以執行以下操作:

while(reader.hasNextLine()){ //checks to make sure there's still a line to be read in the file
    String line=reader.nextLine(); //record that next line
    String[] values=line.split(" "); //split on spaces
    if(values.length==4){
         int val1=Integer.parseInt(values[0]); //parse values
         int val2=Integer.parseInt(values[1]);
         String val3=values[2];
         double val4=Double.parseDouble(values[3]);
         //add these values to your arrays. Might have to "count" the number of lines on a first pass and then run through a second time... I've been using the collections framework for too long to remember exactly how to work with arrays in java when you don't know the size right off the bat.
    }
}

下面是一個示例代碼,用於從文件中讀取值並寫入數組。 示例代碼具有int數組的邏輯,您也可以將其復制到其他數組類型。

package sales;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Sales {

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

        FileInputStream fstream = new FileInputStream("sales.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
        while ((strLine = br.readLine()) != null)   {
            String[] tokens = strLine.split(" ");
            int[] transID = convertStringToIntArray(tokens[0]);
            for(int i = 0 ; i < transID.length ; i++ )
                System.out.print(transID[i]);
        }

    }

    /** function to convert a string to integer array
     * @param str
     * @return
     */
    private static int[] convertStringToIntArray(String str)  {
        int intArray[] = new int[str.length()];
        for (int i = 0; i < str.length(); i++) {
            intArray[i] = Character.digit(str.charAt(i), 10);
        }
        return intArray;
    }
}

除了我的評論,這里有3種方法你不能這樣做

讀入單個數組

    int size = 2;

    // first allocate some memory for each of your arrays
    int[] transID = new int[size];
    int[] transCode = new int[size];
    String[] time = new String[size];
    double[] trasAmount = new double[size];

    Scanner reader = new Scanner(new File("sales.txt"));
    // keep track of how many elements you have read
    int i = 0;

    // start reading and continue untill there is no more left to read
    while(reader.hasNext()) {
        // since array size is fixed and you don't know how many line your file will have
        // you have to reallocate your arrays when they have reached their maximum capacity
        if(i == size) {
            // increase capacity by 5
            size += 5;
            // reallocate temp arrays
            int[] tmp1 = new int[size];
            int[] tmp2 = new int[size];
            String[] tmp3 = new String[size];
            double[] tmp4 = new double[size];

            // copy content to new allocated memory
            System.arraycopy(transID, 0, tmp1, 0, transID.length);
            System.arraycopy(transCode, 0, tmp2, 0, transCode.length);
            System.arraycopy(time, 0, tmp3, 0, time.length);
            System.arraycopy(trasAmount, 0, tmp4, 0, trasAmount.length);

            // reference to the new memory by your old old arrays
            transID = tmp1;
            transCode = tmp2;
            time = tmp3;
            trasAmount = tmp4;
        }

        // read
        transID[i] = Integer.parseInt(reader.next());
        transCode[i] = Integer.parseInt(reader.next());
        time[i] = reader.next();
        trasAmount[i] = Double.parseDouble(reader.next());
        // increment for next line
        i++;
    }

    reader.close();

    for(int j = 0; j < i; j++) {
        System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
    }

如你所見,這是很多代碼。

更好地使用列表,以擺脫重新分配和復制的開銷(在您自己的代碼中的leas)

讀入單個列表

    // instanciate your lists
    List<Integer> transIDList = new ArrayList<>();
    List<Integer> transCodeList = new ArrayList<>();
    List<String> timeList = new ArrayList<>();
    List<Double> trasAmountList = new ArrayList<>();

    reader = new Scanner(new File("sales.txt"));
    int i = 0;

    while(reader.hasNext()) {
        // read
        transIDList.add(Integer.parseInt(reader.next()));
        transCodeList.add(Integer.parseInt(reader.next()));
        timeList.add(reader.next());
        trasAmountList.add(Double.parseDouble(reader.next()));
        i++;
    }

    reader.close();

    for(int j = 0; j < i; j++) {
        System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
    }

你看到這里的代碼有多小? 但它仍然可以變得更好......

sales.txt文件中的sales.txt似乎構成了某個實體的數據元素,為什么不把它們放在一個對象中呢? 為此您可以編寫一個名為Transclass ,有些人會這樣想:

class Trans {
    public int transID;
    public int transCode;
    public String time;
    public double trasAmount;
    @Override
    public String toString() {
        return transID + ", " + transCode + ", " + time + ", " + trasAmount;
    }
}

然后,您可以使用此類來保存從文件中讀取的數據,並將該類的每個對象放在一個列表中。

讀入對象列表

    reader = new Scanner(new File("sales.txt"));
    List<Trans> transList = new ArrayList<>();  
    int i = 0;

    while(reader.hasNext()) {
        Trans trans = new Trans();
        trans.transID = Integer.parseInt(reader.next());
        trans.transCode = Integer.parseInt(reader.next());
        trans.time = reader.next();
        trans.trasAmount = Double.parseDouble(reader.next());
        transList.add(trans);
        i++;
    }

    reader.close();

    for(Trans trans : transList) {
        System.out.println("" + i++ + ": " + trans);
    }

輸出所有3種方法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM