Methods

In this program you'll write a Test class, in which you'll create various methods.

  1. Go into the CS labs (see this map for details) and log onto a Windows machine.
  2. Start up a new project, called Methods, with a main class called Main.java. Refer to Lesson 2 if you are unsure how to do this. You do not need to include javabook2.jar in your class files. But be sure to delete TrivialApplication.java and set Main.java as the main file.
  3. In the blank file Main.java, write the following code:
  4. public class Main {
    
    	public static void main(String[] args) {
    		Test t = new Test();
    	}
    
    }
    
  5. Create another new blacnk text file called Test.java, and add it to the project. You should not set it as the main class, since it is not.
  6. In Test.java, type in the following code:
  7. public class Test {
    
    	public Test() {
    
    		print("is 5 even? ");
    		println("" + even(5));
    		print("is 5 odd? ");
    		println("" + odd(5));
    
    		double d = 42;
    		println("d = " + d);
    		println("d x 3 = " + triple(d));
    		println("d x .5 = " + half(d));
    		println("d x 1.5 = " + threeHalves(d));
    
    		method3();
    		method2();
    		method1();
    
    	}
    
    	private boolean even(int number) {
    		return number % 2 == 0;
    	}
    	
    	private boolean odd(int number) {
    		return !even(number);
    	}
    
    	private double triple(double number) {
    		return 3*number;
    	}
    
    	private double half(double number) {
    		return .5 * number;
    	}
    
    	private double threeHalves(double number) {
    		return triple(half(number));
    	}
    
    	private void method1() {
    		System.out.println("method1() called");
    		method2();
    		method3();
    		System.out.println("method1() finished");
    	}
    	
    	private void method2() {
    		System.out.println("  method2() called");
    		method3();
    		System.out.println("  method2() finished");
    	}
    
    	private void method3() {
    		System.out.println("    method3() called");
    		System.out.println("    method3() finished");
    	}
    
    	public void print(String s) {
    		System.out.print(s);
    	}
    
    	private void println(String s) {
    		System.out.println(s);
    	}
    
    	public String toString() {
    		return "this is a Test object";
    	}
    	
    }
    
  8. Compile and run your program.
  9. Press enter, as the console window says, and the black console window will disappear.