本质上,编写了一个从以下.txt文件中读取值的程序
P1 0 8
P2 1 4
P3 2 9
P4 3 3
p8 4 5
Run Code Online (Sandbox Code Playgroud)
每一行代表一个具有其属性的进程.p1是一个名称,0是p1的arr_time,8是p1的burst_time,如下所示:
public class Process {
private String name;
private int arrive_time= 0;
private int burst_time = 0;
private int remain_time = 0;
public Process (String name, int arr_time, int bur_time) {
this.arrive_time = arr_time;
this.burst_time = bur_time;
this.remain_time = burst_time;
this.name = name;
}
public int getArrTime() {return arrive_time;}
public int getBurTime() {return burst_time;}
public int getRemTime() {return remain_time;}
public String getName() {return name;}
public void decRemTime() {this.remain_time--;}
}
Run Code Online (Sandbox Code Playgroud)
我有以下代码,它应该读取和解析.txt文件.每当它看到一个新行时,它必须向priorityQueue prq添加一个新进程.它解析并成功存储.txt的行,但抛出java.lang.ArrayIndexOutOfBoundsException:1.我尝试跟踪它并调试几个小时失败.我不知道它在哪里传递一个不存在的索引...这是有问题的代码.错误产生部分在while循环中,我在评论中描述了它.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Test {
//Priority READY_QUEUE for the accessed processes
public static PriorityQueue<Process> prq = new PriorityQueue<Process>(5, new Comparator<Process> () {
@Override
public int compare(Process p1, Process p2) {
return p1.getArrTime() - p2.getArrTime();
}
});
public static void main(String[] args) throws IOException {
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Veni\\Desktop\\test\\test.txt\\"));
}
catch (FileNotFoundException fnfex) {
System.out.println(fnfex.getMessage() + "File not found");
System.exit(0);
}
/*
* We get an error here in the ParseInt operation
* immediately following the first while loop iteration
*/
while((line = br.readLine()) != null) {
System.out.println("reentering while loop");
String[] params = line.split(" ");
System.out.println(params[0]);
System.out.println(Integer.parseInt(params[1]));
System.out.println(Integer.parseInt(params[2]));
System.out.println("done");
prq.add(new Process(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]) ));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我非常肯定(从我的追踪中)问题出现在第一次迭代到while循环之后.问题在于ParseInt操作.我完全陷入困境并对此感到困惑.
在使用数组索引之前检查数组的大小如:
String[] params = line.split(" ");
if(params.length < 3){
// your code if length is not as expected
}
Run Code Online (Sandbox Code Playgroud)
回答评论:在吐术之前你应该添加以下条件来检查行是否为空:
if("".equals(line.trim())){
continue;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |