程序代码应该没错的,题目是这样的
~recall that in our part class the supply method returns -1 when there are insufficient stock.
~this is not a good design, as there can be many dfifferent reasons why this method. for example, the quantity requested may be -ve or too large(above preset limt).
~in this case, throwing an exception is more suitable when one or more error states are detected. unlike returning a value(such as -1) it can explicitly indicate the cause of error.
!now modify the supply method to throw exception in two different cases
- insufficient stock
- incorrect quantity requested(assume valid quantity is in range 1...500
~modify the driver class to catch and handle the exceptions.
----------------解决方案--------------------------------------------------------
这个好像是提示还是什么,没看懂
changes needed for supply method
~when the quantity requested <= 0 or >500 throw an excption object as in: throw new Exception("Invalid amount");
~when the sock level is less than quantity requested throw as in: throw new Exception("Insufficient Stock");
~Change the method header to : public double supply(int qty) throws Exception
Changes needed in the calling method
~Place the try-catch within a loop which repeats until done is true. Place the call to supply in a try block as in:
try{
double amt=p.supply(qty);
System.out.println("Cost for supplying" + p.getID() + "=" + amt);
done=true;
}
~Catch the Exception and handle it as in:
-Display the exception
-extract the exception message saving it in a string
-Depending on this message perform appropriate actions
catch(Exception e){
System.out.println(e);
String cause=e.getMessage();
if(cause.indexOf("Insuff")>= 0){
..... ....
}
else if(cause.indexOf("Invalid") >= 0)
...
}
}
----------------解决方案--------------------------------------------------------
提示: 作者被禁止或删除 内容自动屏蔽