[英]Problem reading file in Java with lines of different length
我正在尝试读取文件,但无法从中获得正确的输出。 有人可以告诉我应该如何更改代码以使其正常工作吗? 代码中的 isNum() 函数是一种检查字符串是否为数字的方法(因为我需要将 5 和 10 放在一个单独的变量中)。
编辑:在听取了建议后,我对代码进行了一些更改,现在看起来好多了,但仍然存在一些问题。 下面的代码和输出已更新。
int numEv = 0;
Scanner input = new Scanner(System.in);
ArrayList<String> evtList = new ArrayList<String>();
try {
input = new Scanner(Paths.get("src/idse/Events.txt"));
} catch (IOException e) {
System.out.println(e);
}
try {
while(input.hasNext()) {
String a = input.nextLine();
if (isNum(a)){
numEv = Integer.parseInt(a);
System.out.println(numEv);
}
else if(!a.isEmpty()&&!isNum(a)){
String[] parts = a.split(":");
for (String part : parts) {
evtList.add(part);
}
System.out.println(evtList);
}
if(isNum(a)){
evtList.clear();
}
}
我得到的输出是:
5
[Logins, 2, Total time online, 1, Emails sent, 1, Orders processed, 1]
[Logins, 2, Total time online, 1, Emails sent, 1, Orders processed, 1, Pizza’s ordered online, 0.5]
10
[Logins, 7, Total time online, 5, Emails sent, 9, Orders processed, 15]
[Logins, 7, Total time online, 5, Emails sent, 9, Orders processed, 15, Pizza’s ordered online, 0.9, Logouts, 6]
我想要的输出是:
5
[Logins, 2, Total time online, 1, Emails sent, 1, Orders processed, 1, Pizza’s ordered online, 0.5]
10
[Logins, 7, Total time online, 5, Emails sent, 9, Orders processed, 15, Pizza’s ordered online, 0.9, Logouts, 6]
您应该进行 3 次修复,请按照以下步骤操作:
5
Logins:2:Total time online:1:Emails sent:1:Orders processed:1:Pizza’s ordered online:0.5:
10
Logins:7:Total time online:5:Emails sent:9:Orders processed:15:Pizza’s ordered online:0.9:Logouts:6:
Thud 将根据需要按行分割文件。
System.out.println()
方法:if (isNum(a)){
numEv = Integer.parseInt(a);
System.out.println(numEv);
}
else if(!a.isEmpty()&&!isNum(a)){
String[] parts = a.split(":");
for (String part : parts) {
evtList.add(part);
}
System.out.println(evtList);
}
这将修复你太长的输出,因为它打印了一些不必要的东西。
evtList.clear();
在 while 循环中的每次迭代后添加此行,以使列表仅更新到当前行,而不是之前事件中的所有节点。
根据您在注释中指定的内容(例如,您不能更改输入文件格式),您必须始终检查文件的下一行以查看特定输入代码是否已结束。 我会使用这个技巧在不移动指针的情况下读取下一行。
int numEv = 0;
Scanner input = new Scanner(System.in); // idk what you need this for
ArrayList<String> evtList = new ArrayList<String>();
try {
BufferedReader reader = new BufferedReader(new FileReader(Paths.get("src/idse/Events.txt")));
} catch (IOException e) {
System.out.println(e);
}
try {
while((a= reader.readLine()) != null) {
if (isNum(a)){ // Reading and printing the number
numEv = Integer.parseInt(a);
System.out.println(numEv);
} else if(!a.isEmpty()){ // Getting and storing the code
String[] parts = a.split(":");
for (String part : parts) {
evtList.add(part);
}
}
reader.mark(0);
a = reader.readLine();
if(a == null || isNum(a)) { // If the next line is a number or doesn't exist, we print and clear the code
System.out.println(evtList);
evtList.clear();
}
reader.reset();
}
我希望这有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.