2013-11-25 60 views
1

好的,我急需這裏的幫助。我在大學開始編程課,幾乎完成了這個學期,並且已經理解了大多數東西,但沒有太多困難,但在這種情況下,所有事情都在我頭上。將文件讀取到陣列

我的教授要求我們創建一個程序,讀取包含2個字段的文本文件到數組。第一個字段包含表示星期幾的數字1-7,第二個字段包含那些日子的溫度。

一旦程序讀入文件到數組中,你必須找到一週中每一天的平均溫度(例如5個星期一天都有不同的溫度,平均值是多少?)然後它需要計算高溫和低溫溫度。

完成此操作的程序需要將信息寫入到一個新文件

Day__High__Low __Avg 
1 
2 
3 
4 

現在,我一直在這2周現在教授已經延長了一個星期,我的程序的最後期限明天到期,所以我需要幫助。

我需要的是將txt文件讀入數組的簡單方法,然後我將自己完成邏輯,然後將數組寫入另一個文件。我已經嘗試了十幾件事觀看了幾個視頻,我無法獲得任何工作。

一旦我能夠讀取某些文件並寫入文件,我相信我可以找出完成這項工作的邏輯。

請幫助

試圖somethign類似

try { 
Scanner scanner = new Scanner(new File("inputfile.dat")); 
} 
catch(Exception e) 
{ 
} 
+2

[如何閱讀Java中的文件](http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/)。開始吧! :) – SudoRahul

+0

到目前爲止你做了什麼?我建議你看看這篇文章(http://www.roseindia.net/java/beginners/java-read-file-line-by-line.shtml)和這個[javadoc](http:// docs。 oracle.com/javase/6/docs/api/java/io/FileInputStream.html)。 –

+0

很抱歉,我們不在這裏做任務,但我們將幫助您解決您在任務中遇到的特定問題。但我們需要看到有效的努力。所以,如果你嘗試過一些東西,請告訴我們你的代碼。這個問題似乎很容易解決。因此,您向我們展示您嘗試的內容越快,您就能越快完成作業。 –

回答

0

IO骨架的幾乎任何讀文本,然後輸出文本程序:

Scanner data = new Scanner(new FileInputStream(<file>)); 
while (data.hasNextLine()) { 
    String dataPoint = data.nextLine(); 
    ... 
} 
... 
PrintStream output = new PrintStream(<file>); 
for (...) { 
    output.println(...); 
} 
output.close(); 

你需要添加IO異常的適當的try-catch塊。

+0

試圖弄清楚如何編寫代碼ina commnet – Saint

0

我試圖創建使用掃描儀和PrintWriter的代碼:

import java.awt.PageAttributes; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.PrintWriter; 
import java.util.Scanner; 


public class CalcAvgTemp { 
    public static void main(String[] args) throws FileNotFoundException { 
     File inFile = new File("E:\\inputFile.txt"); 
     File outFile = new File("E:\\outputFile.txt"); 
     int[] day = new int[7]; 
     int[] count = new int[7]; 
     Scanner sc = new Scanner(inFile); 
     sc.nextLine(); // move to second line assuming file is not empty. 
     while(sc.hasNextLine()) { 
      String s = sc.nextLine().trim(); 
      String[] splitStr = s.split(" "); 
      day[Integer.parseInt(splitStr[0])-1] += Integer.parseInt(splitStr[1]); 
      count[Integer.parseInt(splitStr[0])-1]++; 
     } 

     PrintWriter outFileWriter = new PrintWriter(outFile); 
     outFileWriter.println("Day__High__Low __Avg"); 
     for(int i=0;i<7;i++) { 
      int j=i+1; 
      double d = (double)day[i]/count[i]; 
      outFileWriter.println(j + " " + d); 
     } 
     outFileWriter.close(); 
    } 
} 

我使用的輸入文件:

day temp 

    1 20 
    2 30 
    3 40 
    4 20 
    5 60 
    6 30 
    7 10 
    1 34 
    2 34 
    3 32 
    4 34 
    5 45 
    6 34 
    7 23 
    1 12 
    2 10 
    3 20 
    4 23 
    5 67 
    6 23 
    7 12 
    1 26 

我去輸出:

Day__High__Low __Avg 
1 23.0 
2 24.666666666666668 
3 30.666666666666668 
4 25.666666666666668 
5 57.333333333333336 
6 29.0 
7 15.0 
+1

謝謝,它的工作原理,甚至更好,我可以分開重複,並找出如何自己做。如果我被允許的話,你的天賜良機m8會讓你高興。現在要弄清楚如何寫我自己的,並且合併我自己的logi o7 – Saint

+0

@Saint:祝你好運。 – anon