diff --git a/java/week8/exception-output-file/NamesAndAges.txt b/java/week8/exception-output-file/NamesAndAges.txt new file mode 100644 index 0000000..2dcd7a9 --- /dev/null +++ b/java/week8/exception-output-file/NamesAndAges.txt @@ -0,0 +1,5 @@ +Lee 18 +Lua 21 +Mary Beth 19 +Stu 33 +-1 diff --git a/java/week8/exception-output-file/NamesAndAgesUpdated.txt b/java/week8/exception-output-file/NamesAndAgesUpdated.txt new file mode 100644 index 0000000..d19f29d --- /dev/null +++ b/java/week8/exception-output-file/NamesAndAgesUpdated.txt @@ -0,0 +1,4 @@ +Lee 19 +Lua 22 +Mary 0 +Stu 34 diff --git a/java/week8/exception-output-file/main.java b/java/week8/exception-output-file/main.java new file mode 100644 index 0000000..0bcf73b --- /dev/null +++ b/java/week8/exception-output-file/main.java @@ -0,0 +1,94 @@ +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Scanner; +import java.io.FileOutputStream; +import java.io.FileInputStream; +import java.io.IOException; +/* + * Same as the input one and the string vs int one, but now writting to a file + * instead of the screen. +*/ + +public class main { + + public static ArrayList getInput(Scanner scnr){ + + String s = ""; + String name; + int age; + + ArrayList results = new ArrayList(); + + while(true){ + + //Get name or exit + s = scnr.next(); + + if (s.equals("-1")){ + System.out.println(); + break; + } + else{ + name = s; + } + + //Get age + + try{ + age = scnr.nextInt() +1; + } + catch(Exception e){ + System.out.println("Age must be an Integer\n" + + "Setting age to 0 "); + age = 0; + + } + //Finish line + scnr.nextLine(); + + //Add name plus new age to arr + results.add(name + " " + Integer.toString(age)); + + System.out.println(); + } + return results; + } + + public static void main(String[] args) throws IOException { + FileInputStream fileByteStream = null; // File input stream + Scanner inFS = null; // Scanner object + + ArrayList userInputs = new ArrayList(); + + //Get input + System.out.println("Opening file NamesAndAges.txt."); + fileByteStream = new FileInputStream("NamesAndAges.txt"); + inFS = new Scanner(fileByteStream); + + System.out.println("Reading in file and processing"); + + userInputs = getInput(inFS); + + + System.out.println("Closing scanner and writing out results " + + "To NamesAndAgesUpdated.txt"); + fileByteStream.close(); + inFS.close(); + + //Write to file + + FileOutputStream fileStream = null; + PrintWriter outFS = null; + + fileStream = new FileOutputStream("NamesAndAgesUpdated.txt"); + outFS = new PrintWriter(fileStream); + + for (String S:userInputs){ + outFS.println(S); + } + outFS.flush(); + fileStream.close(); + outFS.close(); + } +} +