THINK FIRST·CODE LATER

← All labs

A calculator that never crashes

Problem

Write SafeCalculator. Each input line is an expression a op b with integers and one of + - * / %. A method int apply(int a, String op, int b) computes it and throws IllegalArgumentException("unknown operator '^'") for other operators (division by zero throws ArithmeticException by itself).

main reads lines until the end of input, skips empty lines, and catches each problem separately:

12 / 4 = 3
7 / 0 -> cannot divide by zero
x + 1 -> not a whole number (For input string: "x")
2 ^ 8 -> unknown operator '^'

A line that does not have three parts throws IllegalArgumentException("expected: number operator number"). Use a finally block that prints [3 lines processed] after every third line. End with Done: 2 ok, 3 errors.

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l16-2-data-1.txt

12 / 4
7 / 0
x + 1
2 ^ 8
10 % 3
What your program must print for l16-2-data-1.txt
12 / 4 = 3
7 / 0 -> cannot divide by zero
x + 1 -> not a whole number (For input string: "x")
  [3 lines processed]
2 ^ 8 -> unknown operator '^'
10 % 3 = 1
Done: 2 ok, 3 errors

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l16-2-data-1.txt

Windows PowerShell does not understand <:

Get-Content l16-2-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.