2015-10-27 84 views
2

我有一個任務,我遇到了一些問題。BufferedReader和填充int數組

該程序使用緩衝讀取器,在以前的作業中,我們總是在一行上輸入用戶數據,並使用.split("\\s+")進行分割。這項任務需要在 500個整數在一個單獨的行上,直到它達到零。

我的問題是解析字符串輸入到一個int數組。通常我有一個字符串數組,我設置等於inputValue.split("\\s+"),但教授說我們只需要一個數組(我們的int數組),並且我不知道如何分割輸入,因爲現在我沒有得到所有的輸入到我的int數組中。

int count = 0; 
int intScoresArr[] = new int [500]; 
//String strArray[]; 

while((inputValues = BR.readLine()) != null) { 
    for(int i = 0; i < inputValues.length(); i++) { 
     intScoresArr[i] = Integer.parseInt(strArray[i]); 
     count++; 
    } 
} 
average = calcMean(intScoresArr, count); 
System.out.println(NF.format(average)); 

這裏有一些輸入和我期待的輸出以及當我循環並打印出數組時實際得到的內容。

input: 
    1 
    2 
    3 
    4 
    5 

output: 
    count: 5 
    intScouresArr = 5 0 0 0 0 

expected output: 
    count: 5 
    intScoresArr = 1 2 3 4 5 
+1

如果每行只包含一個數字,那麼'readLine()'將返回。你可以直接''parseInt()'readLine()'('inputValues')返回的字符串。 – Cinnam

+1

你嘗試了沒有內部'for(int i = 0; i

+0

噢!這很有意義。現在你指出,我可以看到爲什麼for循環不必要的哈哈。 – NoobCoderChick

回答

1

如果你期待每行一個整數,你不需要兩個嵌套循環;外部while就足夠了:

int count = 0; 
int intScoresArr[] = new int [500]; 
String line; 

while((line = BR.readLine()) != null) { 
    intScoresArr[count] = Integer.parseInt(line.trim()); 
    count++; 
} 
+0

什麼是line.trim在幹什麼?另外,爲什麼初始化行爲空? – NoobCoderChick

+1

'line.trim()'從行中刪除前導和尾隨空白(這會導致'Integer.parseInt'失敗)。如果你確定輸入不包含多餘的空格,只需使用'Integer.parseInt(line)'。將'line'初始化爲'null'在這裏實際上是多餘的;爲了清晰起見,我編輯了它。 –

+0

好酷。再次感謝你,你已經結束了兩個小時的搜索和試驗!我應該早點問 – NoobCoderChick