For a long time I tried to occupy the try-catch-finally block. I am new to java and am currently learning how to read / write / handle exceptions. In my task, I am trying to read from two separate .txt files. One has countries and a population, while others have countries and a region of the country. This is additionally printed in a new file, which displays information about countries and regions per person.
I'm not sure if I can finally insert a try-catch block. I am currently receiving the error message "Unhandled FileNotFoundException etc.". I tried this for a long time, and just can't get it to work correctly.
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(); } }
Thanks!:)
source share