2010-01-31 58 views
3

嘿。您最近可能會看到我尋找幫助的帖子,但之前我做錯了,所以我要重新開始並從基礎開始。使用字符串標記器從文本文件中設置創建數組?

我想讀的文本文件看起來像這樣:

FTFFFTTFFTFT
3054 FTFFFTTFFTFT
4674 FTFTFFTTTFTF
...等

我需要做的是將第一行放入一個字符串中作爲答案。

接下來,我需要創建一個包含學生ID(第一個數字)的數組。 然後,我需要創建一個與包含學生答案的學生ID平行的數組。

下面是我的代碼,我不知道如何讓它像這樣工作,我想知道是否有人可以幫助我。

public static String[] getData() throws IOException { 
     int[] studentID = new int[50]; 
     String[] studentAnswers = new String[50]; 
     int total = 0; 

     String line = reader.readLine(); 
     strTkn = new StringTokenizer(line); 
     String answerKey = strTkn.nextToken(); 

     while(line != null) { 
     studentID[total] = Integer.parseInt(strTkn.nextToken()); 
     studentAnswers[total] = strTkn.nextToken(); 
     total++; 
     } 
    return studentAnswers; 
    } 

所以在一天結束時,所述陣列結構應該是這樣的:

studentID [0] = 3054
studentID [1] = 4674
...等

studentAnswers [0] = FTFFFTTFFTFT
studentAnswers [1] = FTFTFFTTTFTF

謝謝:)

回答

2

假設您已正確打開文件進行讀取(因爲我看不到讀取器變量是如何初始化的或讀取器的類型如何)並且文件的內容格式良好(根據您的預期),你必須做到以下幾點:

String line = reader.readLine(); 
    String answerKey = line; 
    StringTokenizer tokens; 
    while((line = reader.readLine()) != null) { 
    tokens = new StringTokenizer(line); 
    studentID[total] = Integer.parseInt(tokens.nextToken()); 
    studentAnswers[total] = tokens.nextToken(); 
    total++; 
    } 

當然,如果你爲了避免運行時錯誤(如果該文件的內容是不正確的)添加一些檢查,這將是最好的,如圍繞Integer.parseInt()的try-catch子句(可能會拋出NumberFormatException)。

編輯:我只是注意到你的標題中你想使用StringTokenizer,所以我編輯了我的代碼(用StringTokenizer替換了分割方法)。

2

你可能要考慮一下......

  • 使用Scanner類使用集合類型(如ArrayList)而不是原始陣列令牌化輸入
  • - 陣列有其用途,但他們不太靈活;一個ArrayList具有動態長度
  • 創建一個類來封裝的學生證和他們的答案 - 這保持信息一起,避免了需要保持兩個陣列同步

Scanner input = new Scanner(new File("scan.txt"), "UTF-8"); 
List<AnswerRecord> test = new ArrayList<AnswerRecord>(); 
String answerKey = input.next(); 
while (input.hasNext()) { 
    int id = input.nextInt(); 
    String answers = input.next(); 
    test.add(new AnswerRecord(id, answers)); 
} 
相關問題