我得到了一个NoSuchElementException,现在调试这个,我注意到Car和Carmap被正确地创建了,值也被适当地存储了,所以我不确定ST看不到下一个标记?或者当is看到没有更多的令牌时,它是否停止。
感谢所有人的参与。
Carmap = new HashMap<String,Car>();
//Change file path accordingly
File f = new File("C:\\XXX\\XXX\\XXX\\CarFaxDB.txt");
//Check to see if file exists, else create file
if (f.exists()){
String data[] = readFile(f);
for (int i =0; i<data.length; i++){
if (data[i] != null){
if (i>0){
String line = data[i];
StringTokenizer st = new StringTokenizer(line,",");
String VIN = st.nextToken();
String carMake = st.nextToken();
String carModel = st.nextToken();
int carYear = Integer.parseInt(st.nextToken());
data[i]= line;
Car car = new Car(VIN, carMake, carModel, carYear);
Carmap.put(car.getVIN(), car);
}
}
}
}发布于 2016-03-09 13:27:47
出现错误的原因是,您正在尝试使用nextToken(),但令牌器没有更多的令牌。
在执行nextToken()之前,您应该检查是否有更多的令牌。您可以使用hasMoreTokens()方法来完成。
此外,您应该检查是否获得了一个非空的line,并开始打印它,以查看它是否包含您期望的所有令牌。
以下是更正后的代码片段:
Carmap = new HashMap<String,Car>();
//Change file path accordingly
File f = new File("C:\\Users\\XXX\\Documents\\CarFaxDB.txt");
//Check to see if file exists, else create file
if (f.exists()){
String data[] = readFile(f);
for (int i = 0; i < data.length; i++){
if (data[i] != null){
if (i > 0){
String line = data[i];
if(!StringUtils.isEmpty(line)) {
System.out.println(line);
StringTokenizer st = new StringTokenizer(line,",");
/* Check For More Tokens */
String VIN = st.hasMoreTokens() ? st.nextToken() : null;
/* Check For More Tokens */
String carMake = st.hasMoreTokens() ? st.nextToken() : null;
/* Check For More Tokens */
String carModel = st.hasMoreTokens() ? st.nextToken() : null;
/* Check For More Tokens */
int carYear = st.hasMoreTokens() ? Integer.parseInt(st.nextToken()) : 0;
data[i] = line;
Car car = new Car(VIN, carMake, carModel, carYear);
Carmap.put(car.getVIN(), car);
}
}
}
}
}发布于 2016-03-09 13:37:55
在调用StringTokenizer.nextToken()之前,您必须检查StringTokenizer是否有更多令牌。你可以这样做:
Carmap = new HashMap<String,Car>();
//Change file path accordingly
File f = new File("C:\\Users\\XXX\\Documents\\CarFaxDB.txt");
//Check to see if file exists, else create file
if (f.exists()){
String data[] = readFile(f);
for (int i =0; i<data.length; i++){
if (data[i] != null){
if (i>0){
String VIN, carMake, carModel = null;
int carYear = 0;
String line = data[i];
StringTokenizer st = new StringTokenizer(line,",");
if(st.hasMoreTokens()) {
VIN = st.nextToken();
if(st.hasMoreTokens())
carMake = st.nextToken();
if(st.hasMoreTokens())
carModel = st.nextToken();
if(st.hasMoreTokens())
carYear = Integer.parseInt(st.nextToken());
data[i]= line;
if(VIN != null && carMake != null && carModel != null && carYear > 0)
Car car = new Car(VIN, carMake, carModel, carYear);
Carmap.put(car.getVIN(), car);
}
}
}
}
}请看这个question的答案,它解释了更多。
https://stackoverflow.com/questions/35883555
复制相似问题