我的程序包含几个选项,用于处理有关节目(名称,日期,时间)的用户输入数据。其中一个选项是读取文件并向用户显示其内容。虽然我的程序的这一部分工作,但它没有正确显示(如下所示)。我应该更改程序如何读取文件吗?如果对我的代码有什么改变有任何建议,我会非常感激!谢谢。
这是我的代码:
//Method loadShows
public static void loadShows() throws IOException {
//String to find file
String findFile, file;
//ask for location of file
System.out.println("Enter Show File Location: ");
//Read input
findFile = in.readLine();
file = findFile + "/show.txt";
BufferedReader input = new BufferedReader(new FileReader(file));
x = Integer.valueOf(input.readLine()).intValue();
System.out.println("Loading " + x + " Shows");
for(i = 0; i<=(x-1); i++) {
name[i] = input.readLine();
day[i] = input.readLine();
time[i] = input.readLine();
}
for(i = 0; i<=(x-1); i++) {
System.out.println("Name : " + name[i]);
System.out.println("Day : " + day[i]);
System.out.println("Time(2:30 am = 0230) : " + time[i] + "\r");
}
}
这是输出:
Enter Show File Location:
C:\Users\OneDrive\Desktop\MyFirstJavaProject
Loading 3 Shows
Name : //***As you can see it isn't in order, or displayed correctly***
Day : Suits
Time(2:30 am = 0230) : Monday
Name : 0130
Day : The Flash
Time(2:30 am = 0230) : Thursday
Name : 0845
Day : National Geographic
Time(2:30 am = 0230) : Sunday
这是我的文件内容:
3
Suits
Monday
0130
The Flash
Thursday
0845
National Geographic
Sunday
0525
答案 0 :(得分:1)
您只能使用一个:
public static void loadShows() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\adossantos\\file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
String[] values = everything.split("\n");
for(int i = 0; i < values.length; i+=3) {
if(i + 3 > values.length - 1 )
break;
System.out.println("Name : " + values[i + 1]);
System.out.println("Day : " + values[i + 2 ]);
System.out.println("Time(2:30 am = 0230) : " + values[i + 3] + "\r");
}
} finally {
br.close();
}
}
响应: