import java.io.*; class TidyArithmetic { static InputStreamReader isr; static BufferedReader comingIn; static PrintWriter goingOut; static final String allowableChars = "+-*/"; public static void main ( String [ ] args ) throws Exception { initialiseIO(); char op ; // space to hold a character rep some arithmetic operator int x , y ; // space to store input double answer = 0 ; // space for answer, poss decimal because of div x = getInt() ; op = getOP() ; y = getInt() ; answer = doCalc(x, y, op); System.out.println ( "The value of " +x+ " " +op+ " " +y+ " is " +answer) ; System.out.println ( "Thanks for using \"Multiplier\". Do come again!" ) ; tidyUpIO(); } // end of main method public static void initialiseIO() { isr = new InputStreamReader ( System.in ) ; comingIn = new BufferedReader ( isr ) ; goingOut = new PrintWriter ( System.out , true ) ; } // end of initliseIO method public static void tidyUpIO() throws IOException { isr.close(); comingIn.close(); goingOut.close(); } // end of tidyUpIO method public static double doCalc ( int x, int y, char op) { double temp; switch ( op ) { case '+' : temp = x + y ; break ; case '-' : temp = x - y ; break ; case '*' : temp = x * y ; break ; case '/' : temp = y!=0 ? (double)x/y : Double.NaN; break; default : System.out.println( "Sorry, I didn’t understand what you meant ... bye-bye!" ) ; temp = Double.NaN ; } // end switch statement interpreting the arithmetic operation to be performed return temp; } // end of doCalc method public static int getInt () throws IOException { int temp = 0, numberOfFails = 0; String tryAgain = "Sorry, I didn't understand that as an integer -- please try again." ; String genug = "Sorry, a bad day? ... too many errors. Try again another time!"; boolean messedup = false; do { goingOut.println ( "Please enter an integer" ) ; try { temp = Integer.parseInt ( comingIn.readLine( ) ) ; messedup = false; } catch (NumberFormatException nfe) { messedup = true; numberOfFails++; // to limit the number of bad attempts goingOut.println( numberOfFails < 3 ? tryAgain : genug ); } } while (messedup && numberOfFails < 3); if (messedup) System.exit(1); return temp; } // end of getInt method public static char getOP () throws IOException { int numberOfFails = 0; boolean knownChar = false; String tryAgain = "Sorry, I didn't understand your operator -- please try again, choosing from " + allowableChars.toString(); String genug = "Sorry, a bad day? ... too many errors. Try again another time!"; char temp = '4'; // anything stupid to keep the complier happy! do { goingOut.println ( "Please enter an operator" ) ; temp = ( comingIn.readLine( ) ).charAt(0) ; for (int i=0; i