Q1. (100 pts.) Making Calculator fool-proof Consider the Calculator class given
ID: 3875421 • Letter: Q
Question
Q1. (100 pts.) Making Calculator fool-proof Consider the Calculator class given in Listing 9.5 of the textbook. Your task is to make this program fool-proof: any exceptions that may be generated at run-time will be resolved, any invalid input will be corrected through additional user prompts (i.e., ask for another input value) and all problems encountered during execution will be logged into a log file. A (possibly incomplete) list of cases you should code against is as follows: An operand that cannot be cast to double, .Unsupported operator, . Log file cannot be opened for writing Division by 0 Number of arguments is not exactly 3. Add more cases to this list as you see necessary. Name the log file "calculatorLog.txt" and insert a single line of explanation into this file for every problematic case that has been caught. A sample log file might look like this: The first operand was "hello" - program expected a number. The operator was "%"-only +,-, *, / are supported. Division by 0.Explanation / Answer
import java.util.Scanner; public class JavaProgram { public static void main(String args[]) { float a, b, res; char choice, ch; Scanner scan = new Scanner(System.in); do { System.out.print("1. Addition "); System.out.print("2. Subtraction "); System.out.print("3. Multiplication "); System.out.print("4. Division "); System.out.print("5. Exit "); System.out.print("Enter Your Choice : "); choice = scan.next().charAt(0); switch(choice) { case '1' : System.out.print("Enter Two Number : "); a = scan.nextFloat(); b = scan.nextFloat(); res = a + b; System.out.print("Result = " + res); break; case '2' : System.out.print("Enter Two Number : "); a = scan.nextFloat(); b = scan.nextFloat(); res = a - b; System.out.print("Result = " + res); break; case '3' : System.out.print("Enter Two Number : "); a = scan.nextFloat(); b = scan.nextFloat(); res = a * b; System.out.print("Result = " + res); break; case '4' : System.out.print("Enter Two Number : "); a = scan.nextFloat(); b = scan.nextFloat(); res = a / b; System.out.print("Result = " + res); break; case '5' : System.exit(0); break; default : System.out.print("Wrong Choice!!!"); break; } System.out.print(" --------------------------------------- "); }while(choice != 5); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.