开发者

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:

  • String startCity;
  • String endCity;
  • int capacityUsed;
  • int capacityAvail;
  • int maxCapacity;

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 man开发者_StackOverflow中文版age exceptions.

Thanks


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;


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜