Extension 4.2: Calculator (3 points)



The purpose of this assignment is to give you the skills to index and analyze String s in order to prepare for different scraping tasks. Once you are able to extract information of interest from a target String, you will be ready to query a webpage, save the raw HTML code, and extract relevant information.

For this assignment, you are working on simple arithmetic expressions as String s. Your task is to extract the two integer values and the arithmetic operator from the String and save them as variables of their respective type. You will then compute and print the value of the expression.


Given: String s = "21 + 33";

You must extract 21 and 33 to int variables and + to a char or String variable. Then you will compute and print the expression 21 + 33 = 54


As previously mentioned, the purpose of this assignment is to prepare you for dynamic web scraping tasks. As such, it is expected that you implement this assignment dynamically. In other words, the only assumption you should have about the String you are analyzing is that it will be in the format (Positive Integer)(Arithmetic Operator)(Positive Integer). This implies your implementation should be able to run effectively on an expression containing positive integers of any length. It should also be able to effectively extract any arithmetic operator (+, -, *, /) and print the proper answer. Lastly, your code should be able to deal with possible spaces in the String.

It is important to note that there are many acceptable ways to implement this assignment. It is up to your discretion which way you choose to implement the procedure as long as it abides by the requirements described above.

Listed below are several helpful methods for this assignment. The first is from the String class and is called on the target String t. The other four are static methods. Recall that static methods are not called on a target variable as in the previous method, but rather are called on a generic object of that type.

Demo Video


You should see a calculator package in the src folder.

  1. The file you will modify for this assignment is Calculator.java. It is already in the respository.

  2. Begin by extracting the first integer value from the String using the methods described above. Keep in mind that the integer can be multiple digits. You might be extracting 2 or 274539.

  3. Implement a similar approach for the operator and second integer.

  4. Now that you have the two integers in int variables and the operator in a char or String variable, perform and print the simple arithmetic operation.

For example, if the input is:

2 + 3

then the output should be:

2 + 3 = 5


Be sure to try and test your code with all of the various operations. Some specific examples can be found on the rubric.

You have attempted of activities on this page