Question

In: Computer Science

JAVA Overview This program implements a simple, interactive calculator. Major topics writing a program from scratch...

JAVA

Overview

This program implements a simple, interactive calculator.

Major topics

  • writing a program from scratch
  • multiple methods
  • testing

In this document

  • program logic & program structure (class, methods, variables)
  • input / output
  • assumptions and limitations
  • documentation & style
  • suggested schedule
  • cover letter discussion questions
  • grading, submission, and due date
  • additional notes
  • challenges
  • sample output
  • test plan

Program Logic

  • The program prompts the user to select a type of math problem (addition, subtraction, multiplication, or division), enter the two operands, then calculates and outputs the answer.
  • The program runs until the user does not want to do any more problems.
  • A final tally of problems is printed at the end.

Program Structure and Data

                                                   Calculator class

Constructor

printIntro method

calculate method

printReport method

main method

  • one class named FirstnameLastname_02_CS1Calculator
  • methods: use the method descriptions as English comments in the code, laying out each logic step to be written in Java
    • main: calls constructor, printIntro, calculate, print report
    • constructor: initializes counters to zero, instantiates and initializes a Scanner to read from the keyboard
    • printIntro method: explains program to user
    • calculate method: primary method with a loop until the user is done
      • run a while loop until the user doesn't want to do another problem
        • display operation choices
        • get user choice, echo their choice (print it back on the screen)
          • use if-elses for which operation to print
        • get operands (numbers to use in the math problem)
        • calculate and print answer
          • use if-elses to pick which math formula
        • count operation type (addition, etc.)
          • use if-elses to pick which counter to increment
        • ask if the user wants to do another problem
      • calculate total problems done (addition count + subtraction count + …)
    • printReport method
      • outputs total of each problem done and overall total problems (see sample output)
  • instance (class level) data
    • a Scanner (needs an import statement)
    • 4 ints to count the number of each problem type (addition, etc.)
    • 1 int to hold total problem count
  • local variables: as needed in each method (perhaps none in some methods)

I/O

  • interactive only (keyboard & screen), no data files
  • input
    • user
      • enters the type of problem (addition, etc.)
      • enters two numbers for each calculation
      • enters the decision whether to do more problems
    • the user may enter either uppercase or lowercase for the continuation answer and the problem type selection
    • reading numbers: all input is String type, so it must be converted to int using a parser method from the Integer class:

firstOperand = scan.nextLine();

firstNumber = Integer.parseInt(firstOperand);

  • output (see sample output later in this document)
    • directions to the user about the problem
    • prompts to choose problem type and to enter numbers
    • calculated answer to the math problem
    • summary of problem types completed

Assumptions & Limitations

  • integers only (no real numbers)
  • input numbers and answers will fit in the range of the int data type
  • division is integer division
  • binary operations only (two operands)
  • addition, subtraction, multiplication, division and exit are the only operations supported
  • perfect user: all input will be correct (y or n only; integers only for operands)
  • results are not saved
  • the user will do at least one problem

Test Plan

  • Run the following test data, divided into sessions so that total problem counts can be checked. Restart the program to run each session (set of multiple, related problems). Be sure to check that each result is correct.

  • Simple basic problems, all operations
    • test 1: 111 + 222 = 333
    • test 2: 9999 + 8888 = 18887
    • test 3: 83 / 83 = 1
    • test 4: 84 / 83 = 1
    • test 5: 83 / 84 = 0
    • test 6: 0 – 0 = 0
    • test 7: 500000 + 500001 = 10000001
    • totals
      • Addition problems: 3
      • Subtraction problems: 1
      • Multiplication problems: 0
      • Division problems: 3
      • Total problems: 7

Note: no tests for bad data since this program is guaranteed a perfect user (i.e., no bad input).

Further work / challenges For any you do, run additional test cases to check the new functionality.

  • Add the modulus (remainder) function as a fifth choice for the user. Include a counter for "mod" problems. The math symbol for mod is % (but it does not do anything related to percentage).
  • Experiment with the NumberFormat class to learn how to place commas in results larger than 999 and include that for answers before they are printed.
  • Instead of printing "The answer is", print the result in math format:

3 + 12 = 15

  • Print totals for each type only if the user did any of that type. For example, if they did not do any subtraction problems, don't print the report line listing zero subtraction problems. Use if statements to control printing or not, by looking at the counter for that problem type.

Discussion Questions (cover letter)

  1. Overflow. Find out what happens when you try to add two numbers whose sum exceeds the maximum integer value (just over two billion, one hundred million). Test two billion plus two billion. What result did you get? Explain why overflow happens on a computer.
  2. Explain inexact results on integer division such as:

2 / 5 = 0 and 51 / 25 = 2

  1. What syntax (Java grammar rules) did you have the most trouble getting right?
  2. What semantics (meaning of the code) did you have the most trouble understanding?

Solutions

Expert Solution

Program:

import java.util.Scanner;
class Calculator
{
int a,s,m,d;
  
// Constructor
public Calculator()
{
a=0;
s=0;
m=0;
d=0;
}
  
// printIntro Method For Description
public void printIntro()
{
System.out.println("********** Simple Calculator **********");
System.out.println("1 -> Addition");
System.out.println("2 -> Substratcion");
System.out.println("3 -> Multiplication");
System.out.println("4 -> Division");
}
  
// Calculate Method to perform Operations(+,-,*,/)
public void calculate()
{
String option;
int choice,num1,num2;
  
Scanner input = new Scanner(System.in);
  
do{
printIntro();
  
System.out.println("Enter your Choice:");
choice = input.nextInt();
  
System.out.println("Enter Number 1:");
num1 = input.nextInt();
  
System.out.println("Enter Number 2:");
num2 = input.nextInt();
  
if(choice == 1)
{
System.out.println(num1+" + "+num2+" = "+(num1+num2));
a++;
}
else if(choice == 2)
{
System.out.println(num1+" - "+num2+" = "+(num1-num2));
s++;
}
else if(choice == 3)
{
System.out.println(num1+" * "+num2+" = "+(num1*num2));
m++;
}
else if(choice == 4)
{
System.out.println(num1+" / "+num2+" = "+(num1/num2));
d++;
}
else
{
System.out.printf("\nYou have entered wrong option\n");
}
  
System.out.println("Do you want to perform Another Operation. Press Y to continue:");
option = input.next();
  
}while(option.equals("y") || option.equals("Y"));
  
printReport(a,s,m,d);
}
  
// printReport Method to print the Detailed report
public void printReport(int a,int s,int m,int d)
{
System.out.println("Addition Problems: "+a);
System.out.println("Substratcion Problems: "+s);
System.out.println("Multiplication Problems: "+m);
System.out.println("Division Problems: "+d);
}
  
}

// Driver Class

class FirstnameLastname_02_CS1Calculator.{
  
public static void main(String[] args) {
  
Calculator c = new Calculator();
  
c.calculate();
}
}

Note: Refer the Screenshots for further Clarification


Related Solutions

JAVA make sure file name is FirstnameLastname_02_CS1Calculator. Thank you! Overview This program implements a simple, interactive...
JAVA make sure file name is FirstnameLastname_02_CS1Calculator. Thank you! Overview This program implements a simple, interactive calculator. Major topics writing a program from scratch multiple methods testing In this document program logic & program structure (class, methods, variables) input / output assumptions and limitations documentation & style suggested schedule cover letter discussion questions grading, submission, and due date additional notes challenges sample output test plan Program Logic The program prompts the user to select a type of math problem (addition,...
1. Write a Java program from scratch that meets the following requirements: a. The program is...
1. Write a Java program from scratch that meets the following requirements: a. The program is in a file called Duplicates.java that defines a class called Duplicates (upper/lower case matters) b. The program includes a Java method called noDuplicates that takes an array of integers and returns true if all the integers in that array are distinct (i.e., no duplicates). Otherwise it returns false. Make sure the method is public static. example tests: noDuplicates({}) returns true noDuplicates({-1, 1}) returns true...
ANSWER IN JAVA Write a simple polling program that allows users to rate five topics from...
ANSWER IN JAVA Write a simple polling program that allows users to rate five topics from 1 (least important) to 10 (most important). Pick five topics that are important to you (e.g., political issues, global environmental issues, food, video games). Use a one-dimensional array topics (of type String) to store the five issues. To summarize the survey responses, use a 5-row, 10-column two-dimensional array responses (of type int), each row corresponding to an element in the topics array. When the...
Program 3: Command Line Calculator Topics: Functions or methods, global variables Overview You will build a...
Program 3: Command Line Calculator Topics: Functions or methods, global variables Overview You will build a simple command line calculator. It supports addition (add), subtraction (sub), multiplication (mul), division (div), and calculation of the absolute value (abs). You will use functions to support each type of calculation. You can assume that the numbers are float data types. Software Specifications The user interacts with program by entering a command, followed by some parameters at the command prompt “>”. For example, if...
PYTHON: Im writing a program to make a simple calculator that can add, subtract, multiply, divide...
PYTHON: Im writing a program to make a simple calculator that can add, subtract, multiply, divide using functions. It needs to ask for the two numbers from the user and will ask the user for their choice of arithmetic operation 1- subtract 2- add 3- divide 4- multiply
Java For this project, we want to build a calculator program that can perform simple calculations...
Java For this project, we want to build a calculator program that can perform simple calculations and provide an output. If it encounters any errors, it should print a helpful error message giving the nature of the error. You may use any combination of If-Then statements and Try-Catch statements to detect and handle errors. Program Specification Input Our program should accept input in one of two ways: If a command-line argument is provided, it should read input from the file...
Language: Java(Netbeans) Implement a simple calculator.
Language: Java(Netbeans) Implement a simple calculator.
in JAVA: implement a class called tree (from scratch) please be simple so i can understand...
in JAVA: implement a class called tree (from scratch) please be simple so i can understand thanks! tree(root) node(value, leftchild,rightchild) method: insert(value)
The Project is: 1. Create a new Java program which implements a simple PacMan-type text game...
The Project is: 1. Create a new Java program which implements a simple PacMan-type text game which contains the following functionality: A) At program startup, constructs and displays a 2-dimensional grid using standard array(s) (no collection classes allowed) with the size dynamically specified by the user (X and Y sizes can be different). Places the PacMan in the upper-left corner of the grid facing left All grid cells should have the empty cell character of ‘.’ except for the start...
Create a program named CmdLineCalc.java that works like a simple calculator. You'll run this program from...
Create a program named CmdLineCalc.java that works like a simple calculator. You'll run this program from the command line: $ java CmdLineCalc 1 + 2 3.0 $ java CmdLineCalc 1 - 2.5 -1.5 $ java CmdLineCalc 3 + 4 - 5 2.0 $ java CmdLineCalc 6.5 - 7 + 8 7.5 To keep it simple, your program only needs to support addition (+) and subtraction (-). You may assume that, starting with the first argument, every other argument will be...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT