尝试评估文件输入时StringIndexOutOfBoundsException?

时间:2017-04-11 04:17:17

标签: java

我的行StringIndexOutOfBoundsException得到(line.charAt(0) == 'I'),其中String index is out of range at 0

我不知道该怎么做。

QueueLinkedList<Customer> eventqueue = new QueueLinkedList<Customer>();
QueueLinkedList<Customer> customerqueue = new QueueLinkedList<Customer>();
int numberserved = 0, totalidletime = 0, longestbreak = 0, idletime = 0, linelength = 0, longestline = 0;

try {
    File file = new File("customersfile.txt");
    BufferedReader reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        //empty lines
        while ((line = reader.readLine()) != "") {
            //first line of file
            while ((line = reader.readLine()) != "300") {
                Customer newcust = new Customer();
                if (line.charAt(0) == 'I') {
                    newcust.id = line.charAt(11);
                }
                else {
                    newcust.arrtime = line.substring(14);
                    newcust.setarrtimesecs(newcust.arrtime);
                    newcust.setleavingtime(newcust.arrtime);    
                }
                eventqueue.enqueue(newcust);
            }
        } 
    }
}catch (IOException e) {
    e.printStackTrace();
} 

2 个答案:

答案 0 :(得分:0)

此行为空白,索引0处没有字符,则此字符串为空。您正在执行此行:

line.charAt(0) == 'I'

尝试这样,

if (line.trim().length() > 0 && line.charAt(0) == 'I') {

答案 1 :(得分:0)

在第二个while循环中,您需要trim才能与""进行比较。

while ((line = reader.readLine().trim()) != "") {

并且还与equals进行比较,因为!=运算符会比较引用是否指向同一个对象。