【发布时间】:2015-02-04 02:10:13
【问题描述】:
我所做的是每次用户输入无效的文件名时都会循环执行错误检查:
public static Scanner readFile(String filename){
Scanner stdin = new Scanner(System.in);
File input = new File(filename);
Scanner sc = null;
do {
try {
sc = new Scanner(input);
}
catch(FileNotFoundException e) {
System.out.println("Filename not valid. Please try again:");
filename = stdin.nextLine();
}
} while (!new File(filename).exists());
return sc;
}
我也有足够的方法来读取该文件并将数据放入数组中:
public static CO2Data[] readData(String filename){
File input = new File(filename);
Scanner sc = null;
try{
sc = new Scanner(input);
}
catch(FileNotFoundException e){
System.out.println("Filename not valid");
System.exit(-1);
}
String info = sc.nextLine();
int total = sc.nextInt();
CO2Data[] arr = new CO2Data[total];
for(int i=0; i<10;i++){
arr[i] = new CO2Data();
}
for(int i=0; i<10;i++){
arr[i].setCountry(sc.next());
arr[i].setTotalCO2(sc.nextDouble());
arr[i].setRoadCO2(sc.nextDouble());
arr[i].setCO2PerPerson(sc.nextDouble());
arr[i].setCarsPerPerson(sc.nextInt());
}
return arr;
}
问题是,如果我先输入一个无效的文件名,然后再输入一个有效的名称,程序会说该文件无效,但是如果我先输入一个有效的文件名,那么程序就可以正常工作。那么为什么首先输入一个有效的文件名可以正常工作,但输入一个无效的名称,然后输入一个有效的名称会使程序给我一条错误消息。
【问题讨论】:
标签: java methods error-handling filenames