Page 397 - Introduction to Programming with Java: A Problem Solving Approach
P. 397

                9.7 Problem Solving with Class Members and Instance Members in a Linked List Class (Optional) 363
 //**********************************************************
public static double getAllValues()
{
double totalValue = 0.0;
Agent agent = listOfAgents;
while (agent != null)
{
  }
// end class Agent
}
// end getAllValues
totalValue += agent.getValue();
agent = agent.nextAgent;
  }
return totalValue;
//**********************************************************
public static void addAllValues()
{
}
// end addAllValues
Agent agent = listOfAgents;
while (agent != null)
{
}
agent.addValue();
agent = agent.nextAgent;
     Apago PDF Enhancer
This retrieves location of next object in list.
Figure 9.9b Class methods in Agent class of FundRaiser program
This code and the code in Figure 9.9a are driven by the FundRaiser class in Figure 9.8.
The rest of the code in Figure 9.9a is straightforward. The getValue instance method returns the value in the value instance variable. The addValue instance method assigns a user input to the value instance variable.
Figure 9.9b shows the two class methods in the Agent class. The addAllValues method starts at the object referred to by the class reference variable, listOfObjects. It calls that object’s addValue instance method to retrieve input and add it to that object’s value instance variable. Then it uses the cur- rent object’s nextAgent instance variable to find the next object in the list, and it repeats the process until nextAgent is null. The getAllValues method initializes local variables, totalValue and agent. Then it steps through the objects just like the addAllValues method did, adding the value re- turned by the instance method getValue to totalValue. When the agent reference becomes null, it stops and returns the accumulated totalValue.
The sample session below shows what the program does. Notice that the sequence employed when new objects are added is opposite to the sequence employed when the original objects were created. That’s be- cause each new object is inserted at the head of the linked list, rather than at the tail, as you might normally expect. You could append each new object to the tail end of the list and make the sequences the same, but that would require an additional class variable and more code in the constructor.

































































   395   396   397   398   399