2014-09-04 136 views
-1

我是編程的noobie,我似乎無法弄清楚該怎麼做。讀取文件和處理數據

我寫了一個Java程序,在任何數量從一個文件中的行讀取和生成報告:

值的數量的計數讀 總和 的平均成績(2小數位) 最大值連同相應的名字。 最小值以及相應的名稱。

輸入文件看起來是這樣的:

55527 levaaj01 
57508 levaaj02 
58537 schrsd01 
59552 waterj01 
60552 boersm01 
61552 kercvj01 
62552 buttkp02 
64552 duncdj01 
65552 beingm01 

我的程序運行正常,但是當我在 得分= input.nextInt加();player = input.next(); 該程序停止工作,鍵盤輸入似乎停止工作的文件名。 我想分別讀取每行的int和name,以便我可以處理數據並完成我的任務。我不知道下一步該怎麼做。

這裏是我的代碼:

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.util.Scanner; 

public class Program1 { 

private Scanner input = new Scanner(System.in); 
private static int fileRead = 0; 
private String fileName = ""; 
private int count = 0; 
private int score = 0; 
private String player = ""; 

public static void main(String[] args) { 

    Program1 p1 = new Program1(); 

    p1.getFirstDecision(); 

    p1.readIn(); 

} 

public void getFirstDecision() { //************************************* 

    System.out.println("What is the name of the input file?"); 

    fileName = input.nextLine(); // gcgc_dat.txt 

} 



public void readIn(){   //********************************************* 

    try { 

     FileReader fr = new FileReader(fileName + ".txt"); 
     fileRead = 1; 
     BufferedReader br = new BufferedReader(fr); 

     String str; 

     int line = 0; 

     while((str = br.readLine()) != null){ 

      score = input.nextInt(); 
      player = input.next(); 

      System.out.println(str); 

      line++; 
      score = score + score; 
      count++; 

     } 

     System.out.println(count); 
     System.out.println(score);    

     br.close(); 

    } 

    catch (Exception ex){ 

     System.out.println("There is no shop named: " + fileName);   

    }  

    } 

} 
+1

要比較字符串,你需要使用.equals()不是==。 – user2548635 2014-09-04 22:55:10

+0

我認爲您的任務是指導您將讀取的數據放入列表或字典式結構中以執行報告 - 創建聚合(sum + avg)並對升序和降序(最小+最大)進行排序。 – Filburt 2014-09-04 23:08:40

+1

@DavidPostill在上面。代碼非常混亂。使用BufferReader讀取這個文件,但使用掃描儀讀取變量的操作? – 2014-09-04 23:11:41

回答

1

Scanner使用BufferReader的方式是完全錯誤的

注意:您可以在掃描儀構造函數中使用BufferReader

例如:

try(Scanner input = new Scanner(new BufferedReader(new FileReader("your file path goes here")))){ 

}catch(IOException e){ 
} 

注意:你的文件讀出處理或其他進程必須在try塊,因爲在抓block因爲你的連接被關閉,你不能做任何事情。它被稱爲try catch block with resources

注意

一個BufferedReader將創建一個緩衝區。這應該導致從文件讀取更快的 。爲什麼?因爲緩衝區被文件的內容填充了 。所以,你把更大的文件塊放在RAM (如果你正在處理小文件,緩衝區可以包含整個 文件)。現在,如果掃描儀想要讀取兩個字節,它可以從緩衝區中讀取兩個 字節,而不必向硬盤驅動器請求兩個字節。

一般來說,讀取10個4096個字節 而不是4096個10個字節要快得多。

來源BufferedReader in Scanner's constructor

建議:你可以通過使用BufferReader讀取文件的每一行,並自己做你的分析,也可以使用Scanner類,讓您做解析令牌的能力。

difference between Scanner and BufferReader

作爲提示,您可以使用此示例爲您解析目標

代碼:

 String input = "Kick 20"; 
     String[] inputSplited = input.split(" "); 
     System.out.println("My splited name is " + inputSplited[0]); 
     System.out.println("Next year I am " + (Integer.parseInt(inputSplited[1])+1)); 

輸出:

My splited name is Kick 
Next year I am 21 

希望你能固定程序通過給出的提示。