ZIPCODE,CITY,STATE,LATITUDE,LONGITUDE
ZIPCODE,CITY,STATE,LATITUDE,LONGITUDE
我试图让它能够打开一个地址格式化的文本文件,创建一个循环,按顺序实例化一个具有五个参数的新ZipCode对象,然后将该对象添加到ArrayList myZips。
我觉得至少我的分隔符是错误的。
public void readZipCodeData(String filename){
Scanner inFS = null;
FileInputStream fileByteStream = null;
try{
// open the File and set delimiters
fileByteStream = new FileInputStream(filename);
inFS = new Scanner(fileByteStream);
inFS.useDelimiter(", *");
// continue while there is more data to read
while(inFS.hasNext()) {
// read five data elements
int zipCode = inFS.nextInt();
String city = inFS.next();
String state = inFS.next();
double latitude = inFS.nextDouble();
double longitude = inFS.nextDouble();
ZipCode z1 = new ZipCode(zipCode, city, state, latitude, longitude);
myZips.add(z1);
}
fileByteStream.close();
// Could not find file
}catch(FileNotFoundException error1) {
System.out.println("Failed to read the data file: " + filename);
// error while reading the file
}catch(IOException error2) {
System.out.println("Oops! Error related to: " + filename);
}
}
每次我尝试运行它,它会给我一个 java.util.InputMismatchException: 双精度线上的null(在java.util.Scanner中)错误。有什么想法吗?
答案 0 :(得分:0)
我不熟悉Scanner
输入,而是BufferedReader
。我觉得使用起来很简单,我希望这个解决方案适合你:
Charset charset = Charset.forName("US-ASCII");
try (BufferedReader reader = Files.newBufferedReader(filename, charset)) {
String line = null;
while ((line = reader.readLine()) != null) {
// THIS IS THE CODE FOR EVERY LINE
String[] data = line.split(", ");
int zipCode = Integer.parseInt(data[0]);
String city = data[1];
String state = data[2];
double latitude = Double.parseDouble(data[3]);
double longitude = Double.parseDouble(data[4]);
ZipCode z1 = new ZipCode(zipCode, city, state, latitude, longitude);
myZips.add(z1);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
} catch (NumberFormatException x) {
System.err.format("NumberFormatException: %s%n", x);
}
在此示例中,我使用BufferedReader.readLine()
阅读整行,然后使用String.split()
和Integer.parseInt()
/ Double.parseDouble()
手动解析它。它更直观,而且有效!
由于下面的评论,我想我不能建议上面的答案。但是,我看到有两个潜在的问题:
double
。简单,诚实的错误。,
表示小数点而不是.
尝试切换这些。答案 1 :(得分:0)
尝试这样的事情。不要一次解析一个字段,而是抓住整行,使用分隔符String
将其转换为,
数组,然后解析为int
/ double
。 Scanner.nextLine()
为你抓住整条线。
try{
// open the File and set delimiters
fileByteStream = new FileInputStream(filename);
inFS = new Scanner(fileByteStream);
// read five data elements
String[] data = inFS.nextLine().split(", ");
int zipCode = Integer.parseInt(data[0]);
String city = data[1];
String state = data[2];
double latitude = Double.parseDouble(data[3]);
double longitude = Double.parseDouble(data[4]);
ZipCode z1 = new ZipCode(zipCode, city, state, latitude, longitude);
myZips.add(z1);