gpt4 book ai didi

java - 无法正确读取和显示文件内容

转载 作者:行者123 更新时间:2023-12-02 11:10:42 27 4
gpt4 key购买 nike

我的程序包含几个选项,用于处理有关节目的用户输入数据(名称、日期、时间)。其中一个选项是读取文件并向用户显示其内容。虽然我的程序的这一部分正在工作,但它没有正确显示(如下所示)。我应该更改程序读取文件的方式吗?如果有任何关于我应该更改代码的建议,我将非常感激!谢谢。

这是我的代码:

//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

最佳答案

您只需一个即可:

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();
}
}

回应:

enter image description here

关于java - 无法正确读取和显示文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50645907/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com