KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Jt > examples > patterns > MultiplicationB


1
2
3 package Jt.examples.patterns;
4 import java.util.*;
5 import java.lang.reflect.*;
6 import java.beans.*;
7 import java.io.*;
8 import Jt.*;
9
10 /**
11  * Multiply two numbers using repetitive addition.
12  */

13
14 public class MultiplicationB extends JtObject {
15
16
17
18   public MultiplicationB () {
19   }
20
21
22   private int multiply (int op1, int op2) {
23     int i, o1, o2;
24     int result = 0;
25     int sign = 0;
26
27     if (op1 == 0 || op2 == 0)
28       return (0);
29
30     if (op1 < 0 && op2 < 0) {
31       o1 = -op1;
32       o2 = -op2;
33       sign = 1;
34     } else if (op1 < 0) {
35       o1 = -op1;
36       o2 = op2;
37       sign = -1;
38     } else if (op2 < 0) {
39       o1 = op1;
40       o2 = -op2;
41       sign = -1;
42
43     } else {
44     sign = 1;
45     o1 = op1;
46     o2 = op2;
47     }
48
49     for (i = 0; i < o1; i++)
50         result += o2;
51
52     if (sign > 0)
53       return (result);
54     else
55       return (-result);
56
57   }
58
59
60   /**
61     * Process object messages.
62     * <ul>
63
64     * </ul>
65     */

66
67   public Object JavaDoc processMessage (Object JavaDoc event) {
68
69    String JavaDoc msgid = null;
70    JtMessage e = (JtMessage) event;
71    Object JavaDoc content;
72    Object JavaDoc data;
73    int op1, op2;
74
75
76      if (e == null)
77     return null;
78
79      msgid = (String JavaDoc) e.getMsgId ();
80
81      if (msgid == null)
82     return null;
83
84      content = e.getMsgContent();
85      data = e.getMsgData ();
86
87      op1 = ((Integer JavaDoc) content).intValue ();
88
89      op2 = ((Integer JavaDoc) data).intValue ();
90
91      if (msgid.equals ("MULTIPLY")) {
92        return (new Integer JavaDoc (multiply (op1, op2)));
93      }
94
95
96      if (msgid.equals ("JtREMOVE")) {
97        return (null);
98      }
99
100
101      handleError ("MultiplicationB.processMessage: invalid message id:" + msgid);
102      return (null);
103
104   }
105
106
107
108 }
109
110
111
Popular Tags