2014-08-31 163 views
-1

因此,我試圖從文本文件中將一系列「分數」放入數組,然後按順序排序四行,並編寫其他方法以獲得最高分數,最低,平均等等。println命令在那裏,但我還沒有寫入方法。我一直在工作一整天,我開始混淆自己,現在我在主方法中出現NullPointerException錯誤。任何幫助?將文本文件讀入Java數組

package arrayops1d; 

import java.io.*; 
import java.util.*; 

public class ArrayOps1D { 

    static int scores[]; 
    public static void main(String[] args) throws Exception{ 
     FileReader file = new FileReader("C:/Users/Steve/Documents/" 
       + "NetBeansProjects/ArrayOps1D/Scores.txt"); 
     BufferedReader reader = new BufferedReader(file); 

     String scores = ""; 
     String line = reader.readLine(); 
     while (line != null){ 
      scores += line; 
      line = reader.readLine(); 
     } 


     System.out.println(scores); 
     System.out.println(getTotal()); 
     System.out.println(getAverage()); 
     System.out.println(getHighest()); 
     System.out.println(getLowest()); 
     System.out.println(getMedian()); 
     System.out.println(getPosition()); 
     System.out.println(getDeviations); 
     System.out.println(getStdDev); 


} 
+0

你可以發佈你的文件內容? – 2014-08-31 23:15:55

+0

我不明白你的問題是什麼?你能不能公司告訴發生了什麼事情,我們可以幫忙? – 2014-08-31 23:22:58

+0

我在這裏看不到太多的代碼,它看起來你正試圖將整個文件讀入一個'String'。爲什麼? – 2014-08-31 23:23:58

回答

0

第一期與您的代碼: 在你的文件的路徑,而不是使用/,如果你的程序要在不同的平臺上跑出你必須使用\\或更好File.separator

如果不這樣做,你將有java.io.FileNotFoundException

您正在閱讀的一行行,所以你可以使用split功能和使用Integer.paraseIntFloat.parseFloat每個splited元素轉換並添加到您的陣列

  1. How to use Split in Java
  2. How to convert String to int
+0

不可以。您可以跨平臺使用「/」。 – 2014-08-31 23:30:35

+0

真的嗎?爲什麼它不適合我? – 2014-08-31 23:31:05

+0

是的。你必須舉個例子。 – 2014-08-31 23:32:15

0

這裏有一種方法,你可以從文件中讀取的int值到使用ScannerList一個的Integer陣列 -

Integer[] scores = null; 
File file = new File("C:/Users/Steve/Documents/" 
     + "NetBeansProjects/ArrayOps1D/Scores.txt"); 
if (file.exists() && file.canRead()) { 
    try { 
     List<Integer> al = new ArrayList<>(); 
     Scanner scanner = new Scanner(file); 
     while (scanner.hasNext()) { 
      if (scanner.hasNextInt()) { 
       al.add(scanner.nextInt()); 
      } else { 
       System.out.println("Not an int: " + scanner.next()); 
      } 
     } 
     scores = al.toArray(new Integer[al.size()]); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
} else { 
    System.out.println("Can't find file: " + file.getPath()); 
} 
if (scores != null) { 
    System.out.println("Scores Read: " + Arrays.toString(scores)); 
} 
+0

您如何期待OP向他或她的老師展示此代碼時,老師能接受它? – 2014-08-31 23:31:45

+0

答案不正確。只是暗示將OP引向正確的方向,我相信你同意我的觀點 – 2014-08-31 23:33:22

+0

@KickButtowski再次閱讀OP的問題。除了將'int'讀入數組之外,這個任務還有很多。而且OP實際上發佈了似乎至少嘗試它的代碼。無論是這個,還是展示瞭如何從'String'解析所有'int',坦率地說我認爲這個'Scanner'的例子非常簡單。 – 2014-08-31 23:34:52