爲了讓try-catch-finally塊正常工作,我苦苦掙扎了很長時間。我是一名java初學者,目前正在學習如何讀/寫/處理異常。在我的任務中,我試圖從兩個單獨的.txt文件中讀取。一個有國家和人口,另一個有國家和地區。這將進一步打印到一個新文件,其中顯示有關每個國家和地區的信息。無法使try-catch-finally塊正常工作
我不確定如果我真的可以把終於在try-catch塊內。 目前我收到錯誤消息「未處理的FileNotFoundException等。」。我一直在嘗試這個很長一段時間,只是不能讓它正常工作。
private String country;
private double value;
Scanner in1 = new Scanner(new File("countryPopulation.txt"));
Scanner in2 = new Scanner(new File("countryArea.txt"));
PrintWriter out = new PrintWriter("countryAreaPerInhabitant");
public IOAndExceptionHandling(String line) {
int i = 0;
while (!Character.isDigit(line.charAt(i))) {
i++;
}
this.country = line.substring(0, i - 1).trim();
this.value = Double.parseDouble(line.substring(i).trim());
}
public String getCountry() {
return this.country;
}
public double getValue() {
return this.value;
}
public void printAreaPerPerson() {
try {
try {
while (in1.hasNextLine() && in2.hasNextLine()) {
IOAndExceptionHandling country1 = new IOAndExceptionHandling(in1.nextLine());
IOAndExceptionHandling country2 = new IOAndExceptionHandling(in1.nextLine());
double density = 0;
if (country1.getCountry() == country2.getCountry()) {
density = country2.getValue()/country1.getValue();
out.println(country1.getCountry() + " : " + density);
}
}
}
finally {
in1.close();
in2.close();
out.close();
}
}
catch (FileNotFoundException f) {
System.out.println("FileNotFound!");
}
catch (IOException e) {
e.printStackTrace();
}
}
謝謝! :)
爲什麼要試試? – 2013-05-14 09:30:01