Practice pieces


Methods: calculator

This practice piece is about methods and using the constructor to escape staticness.


Hints:

First, start with the basic template for a main class in which code can use non-static methods:

public class Calculator {

   public Calculator() {
   }

   public static void main(String args[]) {
      new Calculator();
   }
}

Now add in a method called add, that takes in two ints and returns one int. Remember that methods can't overlap or be nested.

Make the method add the two ints passed in, and return the answer.

Finally, call the method from the constructor, and print out the answer that is returned. Remember, if you are inside the same class as a method, you don't need to make an object to call that method (the exception to that is our call to the constructor, above, but this is very rarely done within a class).

If you need more help, here's the answers (or one option, anyhow).


Copy and save what you've done. Next, make yourself an empty IntCalc class, and instead of calling the local add method in your main class, make an object out of the IntCalc class.

Cut and paste the add method from your main class into the IntCalc class.

In your main class, after you've made the IntCalc object, call its add method, and print the returned answer.

Add in more functionality, as you feel.

If you need more help, here's the answers (or one option, anyhow), and some additional tasks.