2013-05-02 86 views
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()]; 


    } 
} 
+2

你是不是你分配輸出端陣列正道!例如,你不想讓'transID'數組的大小爲'350279',那麼掃描程序將讀取的數據作爲第一個int。最後兩行甚至不會編譯,因爲數組創建期望在'['和']之間有一個'int'並且...爲什麼不使用列表? – A4L 2013-05-02 17:30:52

+1

爲什麼不使用'ArrayList'呢? – 2013-05-02 17:35:59

+1

爲什麼不創建一個名爲Transaction的簡單類,它具有一個自定義的構造函數來解析文件中給定行的標記。每行中的數據是相關的,應該保持在一起(依賴於陣列之間的公共索引是次優的)。然後,您可以將所有Transaction對象存儲在動態大小的集合(如Map或List)中,並利用包含Collection類的功能。 – 2013-05-02 17:57:19

回答

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. 
    } 
} 
1

這是很難建立一個數組這種方式,因爲數組有固定大小...你需要知道他們有多少元素都有。如果使用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; 
    } 
} 
+1

使用[Guava](http://code.google.com/p/guava-libraries/),您可以使用'Ints.toArray()'和'Doubles.toArray()'(以及Java內置' List.toArray()'爲'String')。另外,如果你花時間來構造列表,不妨直接使用列表而不是構造數組。如果您希望列表在構建後成爲固定大小,也可以使用Guava的'ImmutableList'。 – dimo414 2013-05-02 18:48:14

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] 
+0

你爲什麼使用原始類型? – durron597 2013-05-02 17:57:25

+0

這是一個示例代碼來展示如何使用它們,當它們想要在代碼中使用時,它們更改爲泛型類型。但我會更新泛型類型的代碼 – NullPointerException 2013-05-02 18:01:11

+0

@ durron597使用泛型類型調用進行編輯 – NullPointerException 2013-05-02 18:02:48

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; 
    } 
} 
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文件中的一行似乎構成某個實體的數據元素,爲什麼不把它們放在一個對象中呢?對於您可以編寫一個名爲classTrans,有些人認爲這樣的:

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 
相關問題