Method Exercise - Exercise

Contact Us or call 1-877-932-8228
Method Exercise - Exercise

Method Exercise

Duration: 5 to 10 minutes.
  1. Create a class called Calculator.
  2. In it create a method called add that accepts two double parameters, adds them together, and returns the result - mark it as public and static, and returning a double.
  3. In a similar manner, create methods called subtract, multiply, and divide.
  4. In main, create three double variables a, and b, initialized with values of your choice, and c, which we can leave uninitialized.
  5. Call each of your methods in turn, passing a and b, and accepting the returned value into c, and printing all three values.

Solution:

Solutions/Basics/Calculator.java
public class Calculator {
	public static void main(String[] args) {
		double a = 10.0, b = 20.0, c;
		c = add(a, b);
		System.out.println(a + " + " + b + " = " + c);
		c = subtract(a, b);
		System.out.println(a + " - " + b + " = " + c);
		c = multiply(a, b);
		System.out.println(a + " * " + b + " = " + c);
		c = divide(a, b);
		System.out.println(a + " / " + b + " = " + c);
	}
	
	public static double add(double x, double y) {
	  return x + y;
	}
	public static double subtract(double x, double y) {
	  return x - y;
	}
	public static double multiply(double x, double y) {
	  return x * y;
	}
	public static double divide(double x, double y) {
	  return x / y;
	}
}
Next