package assignment_9_muratore; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.util.Scanner; public class Problems { // CHP 14 EX 3 public static void division() { Scanner stdIn = new Scanner(System.in); int n, d, q; System.out.println("Enter numerator: "); n = stdIn.nextInt(); System.out.println("Enter divisor: "); d = stdIn.nextInt(); try { q = n / d; System.out.println(q); } catch (ArithmeticException e) { System.out.println("Error, but keep going anyway."); } stdIn.close(); } // CHP 14 EX 4 public static void division2() { Scanner stdIn = new Scanner(System.in); double n = 0; int d = 0; boolean OK = false; while (OK == false) { try { System.out.print("Enter numerator: "); n = stdIn.nextDouble(); while (d == 0) { System.out.print("Enter divisor: "); d = stdIn.nextInt(); if (d == 0) System.out.println("Can not divide by 0."); } OK = true; } catch (InputMismatchException e) { System.out.println("Invalid input.. try again"); d = 0; n = 0; OK = false; // required to discard data stdIn.next(); } } System.out.println(n / d); stdIn.close(); } // CHP 15 EX 3 public static void testWriter() { String[] churchill = {"Before Alamein we never had a victory.", "After Alamein we never had a defeat."}; PrintWriter fileOut; try { // Append is false to start fileOut = new PrintWriter("elAlamein.txt"); for (String line : churchill) { fileOut.println(line); } fileOut.close(); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } } // CHP 15 EX 4 public static void appendWriter() { FileWriter fileOut; int year = 1942; try { fileOut = new FileWriter("elAlamein.txt", true); fileOut.write("Year " + Integer.toString(year)); fileOut.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } public static void main(String[] args) { System.out.println("Running Division"); division(); System.out.println("Running Division2"); division2(); System.out.println("Running testWriter"); testWriter(); System.out.println("Running testAppend"); appendWriter(); } }
Sunday, May 4, 2014
Assignment 10
Subscribe to:
Comments (Atom)