2014-03-05 152 views
1

我需要讓我的程序讀取一個文件,然後獲取字符串中的數字並將它們排序爲數組。我可以讓我的程序讀取文件並將其放到一個字符串中,但這就是我卡住的地方。所有數字都在文件的不同行上,但在字符串中顯示爲一個長整數。這是我到目前爲止有:從文件中獲取數字並對它們進行排序

public static void main(String[] args) { 

    String ipt1; 
    Scanner fileInput; 
    File inFile = new File("input1.dat"); 

    try { 
     fileInput = new Scanner(inFile); 
     //Reads file contents 
     while (fileInput.hasNext()) { 
      ipt1 = fileInput.next(); 
      System.out.print(ipt1); 
     } 
     fileInput.close(); 
    } 
    catch (FileNotFoundException e) { 
     System.out.println(e); 
    } 
} 
+0

那麼什麼是你的問題? – Idris

+0

@Srink我如何讀取文件並將每行放入數組元素中? – user2848462

回答

0

如果您的任務只是從某個文件獲取輸入,並且您確定文件具有整數,請使用ArrayList。

Scanner fileInput; 
ArrayList<Double>ipt1 = new ArrayList<Double>(); 
File inFile = new File("input1.dat"); 

try { 
    fileInput = new Scanner(inFile); 
    //Reads file contents 
while (fileInput.hasNext()){ 
    ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList 
    System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got. 
} 
fileInput.close(); 

} 
catch (FileNotFoundException e){ 
    System.out.println(e); 
} 

//Sorting time 
//This uses the built-in Array sorting. 
Arrays.sort(ipt1); 

但是,如果你確實需要拿出在最後一個簡單的數組,但可以使用的ArrayList,您可以添加以下內容:

Double actualResult[] = new Double[ipt1.size()]; //Declare array 
for(int i = 0; i < ipt1.size(); ++i){ 
    actualResult[i] = ipt1.get(i); 
} 
+0

即時得到的誤差:異常在線程「主要」 java.lang.Error的:未解決編譯問題: \t的方法排序(INT [])中的類型數組是不適用的參數(ArrayList的) \t類型不匹配:不能從double轉換爲int \t ArrayList 類型中的方法get(int)不適用於參數(雙數) – user2848462

+0

數據類型實際上是雙倍數據類型,所以我進入並更改了它,這可能是什麼影響它? – user2848462

+0

如果您輸入雙打,您需要修改代碼中的一些內容。我將編輯更改。 – SWPhantom

2

我建議使用fileInput.nextInt()或者你想讓他們,使他們在一個數組,並使用內置的有點像數組任何類型的閱讀作爲數字類型的值。分類。除非我錯過了關於這個問題的更微妙的一點。

+0

輸入列表的大小可能未知。如果是這種情況,請使用ArrayList。 – SWPhantom

+0

有效。我沒有想過這個特別的呃逆。 – Irisshpunk

+0

啊,好吧,閱讀他們作爲數字類型幫助我解決了我的第一個問題,但現在我如何創建每行的值,因爲列表長度不一(多個文件將在此程序中測試) – user2848462

相關問題