2015-10-04 48 views
0

我需要將多行輸入存儲到同一個數組中。在循環繼續存儲每個新進線陣列,直到哨兵值在輸入到目前爲止,我有這樣的代碼:我需要將每個輸入的行存儲到同一個數組中

 while(!students.equals("zzzz") && !students.equals("ZZZZ")){ 
     students = br.readLine(); 
     studentInfo = students.split("\\n"); 

     } 
     System.out.println (studentInfo[0]); 

這一切的確,當我鍵入定點值(ZZZZ或ZZZZ)在最後打印出zzzz,因爲它將sentinel值存儲到第一個數組位置。我錯過了什麼?編號喜歡能夠輸入任意數量的行,並訪問這些行中的每一行,並通過調用它來操作字符串(studentInfo [5]或studentInfo [55])。請幫助

+0

必須在使用數組?考慮到行數是一個變量。 – pelumi

+0

使用一個列表,特別是一個ArrayList。完成後,可以使用ArrayList的toArray()方法。 –

+0

我不知道我還可以如何存儲每行輸入,並在以後不使用數組時使用它。在輸入所有信息後,我需要能夠查找學生30(數組值29)的信息,然後處理該字符串輸入並將其與另一個字符串 –

回答

0

根據定義,br.readLine()不會換行符返回任何東西,所以這段代碼:

students = br.readLine(); 
studentInfo = students.split("\\n"); 

總是會導致studentInfo是大小爲1的數組,其第一個(也是唯一一個)元素無論在students

而且,你是更換studentInfo每一個循環,所以它始終擁有最後行中輸入,這在邏輯上必須是"zzzz""ZZZZ"

要解決這個問題,你應該使用List,它可以自動增加大小(基本上你應該避免使用數組)。

試試這個:

List<String> studentInfo = new LinkedList<>(); 
String student = ""; 

while (!student.equalsIgnoreCase("zzzz")) { 
    student = br.readLine(); 
    if (!student.equalsIgnoreCase("zzzz")) 
     studentInfo.add(student); 
} 

System.out.println (studentInfo); 

while循環是一個有點笨拙,因爲student變量必須在循環(即使它只是在循環需要)之外聲明和條件必須重複(否則你的數據將包含終止信號值)。

它可以表示爲一個for循環更好:

for (String student = br.readLine(); !student.equalsIgnoreCase("zzzz"); student = br.readLine()) 
     studentInfo.add(student); 

還要注意的字符串比較使用equalsIgnoreCase()

0

我已經對你的代碼和細微的變化如何可以做到這一點補充意見:

List<String> studentInfo = new ArrayList<>(); //use arraylist since you don't know how many students you are expecting 
//read the first line 
String line = ""; //add line reading logic e.g. br.readLine(); 
while(!line.equalsIgnoreCase("zzzz")){ //check for your sentinel value 
    line = br.readLine(); //read other lines 
    //you can add an if statment to avoid adding zzzz to the list 
    studentInfo.add(students); 
} 
System.out.println("Total students in list is: " + studentInfo.size()); 

System.out.println (studentInfo); //print all students in list 
System.out.println (studentInfo.get(29)); //print student 30 
相關問題