Sams Teach Yourself C in 21 Days

(singke) #1
Working with Java Classes and Methods 729

BD5


5: public void displayText(String message, boolean newline) {
6: // Displays message on the console, moving to
7: // the start of a new line after message only
8: // if newline is true.
9: if (newline)
10: System.out.println(message);
11: else
12: System.out.print(message);
13: }
14:
15: public double halfOf(double value) {
16: // Returns half of its argument.
17: return value / 2;
18: }
19:
20: public long sumOf(long value1, long value2) {
21: // Returns the sum of its arguments.
22: long result;
23: result = value1 + value2;
24: return result;
25: }
26: }

LISTINGB5.4 MethodsDemo.java demonstrates using class methods
1: import java.lang.Double;
2: import java.lang.Long;
3:
4: public class MethodsDemo {
5: public static void main(String args[]) {
6: ClassWithMethods The_Class;
7: String temp;
8: double d;
9: long l;
10:
11: The_Class = new ClassWithMethods();
12: The_Class.displayText(“Using ClassWithMethods:”, true);
13: The_Class.displayText(“Half of 99 is “, false);
14: d = The_Class.halfOf(99);
15: temp = Double.toString(d);
16: The_Class.displayText(temp, true);
17: The_Class.displayText(“The sum of 12345 and 997766 is “, false);
18: l = The_Class.sumOf(12345, 997766);
19: temp = Long.toString(l);
20: The_Class.displayText(temp, true);
21: }
22: }

LISTINGB5.3 continued

40 448201x-Bonus5 8/13/02 11:23 AM Page 729

Free download pdf