user4256847
user4256847

Reputation:

Using array names correctly in for each loop

Given the following example code, please help me answer the following questions with hints

 public class Coin
    {
    private String myColor;
    private int mySideOne;
    private double mySideTwo;


    public Coin(String Color, int SideOne, double SideTwo)
    {
    myColor= Color;
    mySideOne = SideOne;
    mySideTwo = SideTwo;
    }
    //accessors getColor(), getSideOne(), and getSideTwo()

}

public class Total
{
private int myNumCoins;
private Coin[] moneyList;

//constructor
public Total(int myCoins)

{

myNumCoins = numCoins;
moneyList = new Coins[numCoins]
String color;
int mySideOne;
double mySideTwo;
for (int i = 0; i<numCoins; i++)
{




}
}

**

Question:

**

//Returns total amount for Coins 
public double totalMoney()
{
double total = 0.0;
/* code to calculate 
return total;
}
}

Which represents correct / code to calculate amount */ in the totalMoney method?

 A. for (Coin t: moneyList)
    total+= moneyList.getSideTwo();

    B. for (Coin t: moneyList)
    total+=t.getSideTwo();

I think A is right because the "t" in B. doesn't exist in the code. How am I wrong?

Upvotes: 0

Views: 83

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Let's evaluate the code using A.:

public double totalPaid()
{
    double total = 0.0;
    for (Ticket t:tickList)
        total+= tickList.getPrice();
    return total;
}

tickList is an array of Tickets. An array is an object which only has a static final field called length. So, tickList cannot have getPrice. This means, option A doesn't compile.

Let's evaluate the code using B.:

public double totalPaid()
{
    double total = 0.0;
    for (Ticket t:tickList)
        total+=t.getPrice();
    return total;
}

Here you state:

I think A is right because the "t" in B. doesn't exist in the code. How am I wrong?

In fact, t is a variable declared and used in the enhanced for loop statement. t is from type Ticket and it will take the value of each Ticket object reference stored in tickList. The enhanced for loop can be translated to this form for arrays:

for (int i = 0; i < tickList.length; i++) {
    Ticket t = tickList[i];
    //use t in this scope
    //in this case, it's used to accumulate the value of total
    total += t.getPrice();
}

Which makes B as the solution for this problem.

Upvotes: 3

haley
haley

Reputation: 1175

The answer is B because you declare t in your loop when you say Ticket t. The loop iterates the ticketList and t will stand for each Ticket in the list.

Upvotes: 2

Related Questions