java怎么从for语句中获取返回值,我第一个方法中返回了lines可是 打印的时候只打印了[]
问题描述:
package hotel1;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import hotel.CloseStreamMethod;
public class ImportData{
public static 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 += 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) {
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);
}
}
答
try 语句块内要lines初始化
答
......................文件是否存在
答
看代码没有问题,可能是catch分支报异常了,查看下空指针执行的是哪一行,哪个对象为空。
答
需要判断row是否为null
答
打断点在main中运行的时候进行调试 一步一步的进行看看 哪里出现问题了 不就行了。