haohaoxueBC
haohaoxueBC
2019-03-07 21:05

java从文本中获取内容放入容器中,但是打印容器的时候只打印出了文本最后一行。

  • java

**下面两张图是关于我删掉了lines = "";和加了lines += lines;的情况,最下面两行字还有具体解释,谢谢各位能浏览我的问题
**

问题出来return值上面,怎么能成功的return lines

package hotel1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import hotel.CloseStreamMethod;

public class ImportData{
public ArrayList roomsLists = new ArrayList();

public static void main(String[] args) {
    ImportData ip = new ImportData();
    ip.importRooms();
}


public String importData(){

    File src  = new File("/Users/handsomeboy/eclipse-workspace/Coursework/src/hotel1/rooms.txt");

    BufferedReader br = null;

    String lines = null;
    try {
        br = new BufferedReader(new FileReader(src));
        String line = null;
        while((line = br.readLine()) != null) {
            lines = "";
            lines += line;
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        CloseStreamMethod csm = new CloseStreamMethod();
        csm.close(br);
    }
    return lines;
}
public void importRooms() {

    String[] content = importData().split("\n");
    for (String row : content) {
        if(row != null) {
        String[] contents = row.split(",");
          if (contents.length == 5) {
            roomsLists.add(new Rooms(Integer.parseInt(contents[0]),
                    RoomType.valueOf(contents[1].toUpperCase()),
                    Double.parseDouble(contents[2]),
                    Integer.parseInt(contents[3]),contents[4]));
          }
        }
    }
    System.out.println(roomsLists);
}

}

输出内容:
[
RoomNumber: 301, Type: FAMILY, Price: 90.0, Capacity: 4, Facilities: own bathroom]

文本内容:
101,double,80.00,2,own bathroom
102,double,80.00,2,own bathroom
103,twin,70.00,2,shared bathroom
104,twin,70.00,2,shared bathroom
201,double,80.00,2,own bathroom
202,single,70.00,1,own bathroom
301,family,90.00,4,own bathroom

图片说明![!
图片说明
加了+号的一开始试过但是没有用,还有不加lines = "";不会打印出字符串,真的试了很多很多方法,但是改不出来,感谢各位能帮忙debug.

补充一下如果不加lines = "";的话就不能return lines,加了才能成功返回lines值,我也不知道什么,如果不加lines = ""; 打印imporData是可以成功答应所有的内容,
但是不能返回lines的值。

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答