0

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

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()];


    }
}
4

5 回答 5

1

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

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;
    }
}
于 2013-05-02T17:42:37.900 回答
1

使用数组列表,因为数组具有固定大小,并且使用 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]
于 2013-05-02T17:45:20.620 回答
0

这是从文件中读取值并写入数组的示例代码。示例代码具有 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;
    }
}
于 2013-05-02T17:58:47.460 回答
0

除了我的评论,这里还有 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));
    }

如您所见,这是很多代码。

最好使用列表,从而摆脱重新分配和复制的开销(至少在您自己的代码中)

读入单个列表

    // 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似乎构成了某个实体的数据元素,为什么不把它们放在一个对象中呢?为此,您可能会写一个classnamed Trans,有些人会这样想:

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
于 2013-05-02T18:17:38.203 回答
0

您需要一个 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.
    }
}
于 2013-05-02T17:38:04.683 回答