2017-04-02 138 views
0

我在理解Java如何使用Scanner讀取文件中的行以及希望在混淆日子後得到一些解釋方面遇到一些困難。使用掃描儀讀取文件

我有一個包含一個名稱,然後5雙打一行.txt文件。我試圖弄清楚如何將每個變量分配給循環中的變量,以便我可以處理數據。我的目標是從這些行中實際獲取數據,並將它們作爲參數傳遞給另一種驗證方法,因此如果有更簡單的方法可以做到這一點,那麼我就是所有人。我覺得我無法找到一種方法來迭代nextLine中的每一件事,只是遍及整條線本身。我正在嘗試在不使用數組的情況下執行此操作,以下是我現在使用的相關代碼片段。

Scanner inputFile = new Scanner(file); 

while (inputFile.hasNext()) 
    { 
     String line = ""; 
     accumulator++; 
     Scanner split = new Scanner(inputFile.nextLine()); 

     while (split.hasNext()) 
     { 

     } 



     stockName = inputFile.next(); 
     shares = inputFile.nextDouble(); 
     purchasePrice = inputFile.nextDouble(); 
     purchaseCommission = inputFile.nextDouble(); 
     salesPrice = inputFile.nextDouble(); 
     salesCommission = inputFile.nextDouble(); 

     System.out.println(stockName); 
     System.out.println(shares); 
     System.out.println(purchasePrice); 
     System.out.println(purchaseCommission); 
     System.out.println(salesPrice); 
     System.out.println(salesCommission); 


     System.out.print(line); 
     System.out.println(""); 
     // checkValidity(line); 
    } 

我有一個很難提出和闡明什麼,我不知道,所以任何和所有幫助感激......我字面上一直在這三天我在一堵牆上。

編輯:

文本文件的佈局看起來像這樣

DELL: Dell Inc 
125 25.567 0.025 28.735 0.025 
MSFT: Microsoft 
34.1 -15.75 0.012 15.90 0.013 

回答

1

你幾乎沒有。您需要刪除該行:

while (split.hasNext()) 
{ 

} 

這將消耗所有給予拆分的元素。您需要將此分配給所有的元素,如stocksalesPrice

因此,外內新的代碼段while循環

stockName = inputFile.nextLine(); 
    Scanner split = new Scanner(inputFile.nextLine());   

    shares = split.nextDouble(); 
    purchasePrice = split.nextDouble(); 
    purchaseCommission = split.nextDouble(); 
    salesPrice = split.nextDouble(); 
    salesCommission = split.nextDouble(); 

因爲,你是逐行讀取線,也確保外部while循環看起來像:

while (inputFile.hasNextLine()) { 

} 
+0

該文件實際上是佈局,以便名稱在一行,下一行是我需要的所有數據。我嘗試將stockName切換到split.nextLine(),但是它會爲NoSuchElementException引發關於下一行(份額)的錯誤。任何想法爲什麼?不應該stockName只消耗整條線,然後自動移動到下一行? – Josh

+0

@Josh在您的評論後編輯 – bsd