fitzbutz
fitzbutz

Reputation: 976

Simple exercice with exceptions in java

Here's the problem to solve: a method of a class that represents a gas network. This class manages objects of type Line that represent each single gas supply line. An object of type Line is represented by the following members:

The method I'm having trouble implementing is:

boolean carry(String city1, String city2, int capacity)

Consider all the lines from city1 tocity2. For each of these lines try using capacity with the method use() (I don't think it's necessary to know how use() works ). If use() throws the exception CapacitaSuperataException search other lines between city1 and city2, if there are no other lines use() must return False. If a call to use() does not throw CapacitaSuperataException means that the line was assigned the capacity, and the method returns True.

I tried some solutions but I don't know how to manage exceptions.

Thanks

Upvotes: 1

Views: 358

Answers (2)

Daniel
Daniel

Reputation: 3057

Try using the try-catch inside a loop covering all suitable lines in your carry-Method:

for (Line line : getLines("start", "end"))
{
  try
  {
    line.use(cap);
    System.out.println("Line used, great!");
    return true;
  }
  catch (CapacitaSuperataException e)
  {
    System.out.println("Line full, try next");
  }
}
System.out.println("No line found");
return false;

Upvotes: 1

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

public void use(int desiredCapacity) throws CapacitaSuperataException {
    if(desiredCapacity > maxCapacity) throw CapacitaSuperataException 
    ...
}
public void example() {
    try {
    this.use(999999)
    } catch(CapacitaSuperataException) { /* show error message */ }
}

Upvotes: 0

Related Questions