Commit f1d1709e authored by Martin Deinhofer's avatar Martin Deinhofer
Browse files

Fixed opening files

Provocate parse error: one line in file money is d
parent 6e6407e4
2
3
5
d
10
\ No newline at end of file
package java_exercises4_2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
......@@ -7,43 +8,43 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class MoneyDemo {
private static final String inputFileName = "money";
private static final String outputFileName = "sum";
public static void main(String[] args) {
try (
BufferedReader in = new BufferedReader(Files.newBufferedReader(Paths.get(inputFileName), Charset.forName("UTF-8")));
PrintWriter out = new PrintWriter(Files.newBufferedWriter(Paths.get(outputFileName), Charset.forName("UTF-8"), StandardOpenOption.CREATE))
) {
public static void main(String[] args) {
/*
* Always use try-with-resources statement, if possible. This way the files will be closed automatically
* in case of an exception and also if everything goes fine.
*/
try (BufferedReader in = new BufferedReader(
Files.newBufferedReader(Paths.get(inputFileName)));
PrintWriter out = new PrintWriter(Files.newBufferedWriter(Paths.get(outputFileName)))) {
double sum = 0;
String input;
while((input = in.readLine()) != null) {
//Read line by line
while ((input = in.readLine()) != null) {
try {
sum += Double.parseDouble(input);
} catch(NumberFormatException e) {
System.out.println("NumberFormatException: For input string: " + input);
//Sum up lines
sum += Double.parseDouble(input);
} catch (NumberFormatException e) {
//If the line is not parseable, skip it
System.out.println("NumberFormatException: Skipping line: " + input);
continue;
}
}
//Write out sum to the output file
out.write("sum = " + sum);
System.out.println("Sum = " + sum);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Could not read file: "+e.getMessage());
}
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment