This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'm relatively new to java and I am currently struggling to get my head around the scanner and throwing exceptions. I have written the
below code but every time I try running my test I get a failure message. Is it possible one of you guy could tell me where Im going wrong?
Your test code expects that creating a Triangle, using the constructor of the Triangle class, throws a TriangleException if the input is wrong.
But in the constructor of your class Triangle you're never throwing that exception. The constructor is also not calling the validate method, which might throw the exception. You'll have to call the validate method from the constructor.
Hi thanks for your advice. I have modified my code and now it is throwing an exception in the correct manner.
However, I am now having difficultly in writing the product code to throw the correct exception.
I wish to throw an exception for "too many parameters" and "too few parameters" as we know a triangle should take 3 parameters.
This is what I have come up with so far. The code I thought would work is in my previous post.
Is it possible you could help me throw those two exceptions?
In line 12, why are you doing new Scanner("0,0,0")? Aren't you supposed to parse the paramentersstring that's passed to the constructor?
Look at what your code is doing now:
Line 12: Make a scanner to parse the string "0,0,0" (this is most likely not what you meant)
Line 15: A loop that iterates over each number found by the scanner
Line 16: You get the next number in a variable called num
Line 18: If this number is 0, then...
Line 20: ...you throw a TriangleException with the message "Too many parameters"
This seems to be totally different from what you intend the code to do.
So, in practice, this means: it's going to parse the string "0,0,0", then in line 16 num gets assigned the first "0" from this string, in line 18 it notices that the number is 0, and in line 20 the exception is thrown.
Joined: Apr 03, 2012
Thank you Sir I have realized the errors of my ways.