2015-10-04 46 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 
相关问题