Java: Math Operation

In today’s class, our project is to realize an math calculator. The requirement is:

  1. define an interface MathCalculation to declare four basic math calculation methods, which are:
    1. add
    2. subtraction
    3. multiply
    4. divide
  2. create a class Calculator which implements MathCalculation;
  3. create a class CalculationHandler to print the input and output

Please check the code:

/**
* interface
*/
package com.java4kids.tools;
interface MathCalculation {

public int add (int a, int b);
public int subtract (int a, int b);
public int multiply (int a, int b);
public double divide (int a, int b);

}

/**
* class: did you see something different in divide
*/
package com.java4kids.tools;

public class Calculator implements MathCalculation {

public int add(int a, int b) {

// TODO Auto-generated method stub

return a+b;

}

public int subtract(int a, int b) {

// TODO Auto-generated method stub

return a-b;

}

public int multiply(int a, int b) {

// TODO Auto-generated method stub

return a*b;

}

public double divide(int a, int b) {

// TODO Auto-generated method stub

if (b != 0){

return (double)a/(double)b;

} else {

System.out.println(“Warning! The divider can not be zero!”);

return -999999999;

}

}

}

/**
* class:CalculationHandler
*/

package com.java4kids.tools;

public class CalculationHandler {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Calculator myCalculator = new Calculator();

int inputA = 5;

int inputB = 3;

System.out.println(“inputA = “ + inputA);

System.out.println(“inputB = “ + inputB);

System.out.println(“inputC = “ + inputC);

System.out.println(“inputA + inputB = “ + myCalculator.add(inputA, inputB));

System.out.println(“inputA – inputB = “ + myCalculator.subtract(inputA, inputB));

System.out.println(“inputA * inputB = “ + myCalculator.multiply(inputA, inputB));

System.out.println(“inputA / inputB = “ + myCalculator.divide(inputA, inputB));

}

}

Homework:
Can you please implement a method for exponent calculation! We can discuss in the next week!

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s