I would guess because the method setPrice() is never called. You can test that by putting a System.out.println() as the first line of the method. But notice that when you create the Car object, you don't use setPrice().
All things are lawful, but not all things are profitable.
Got it working,bye adding the set method to the constructor.
Exception in thread "main" java.lang.IllegalArgumentException: Error price too high!
Is there anyway for to just print out the Error message "Error price too high !" instead of the rest ?
You will have to alter the setPrice() method because you are calling a public method from the constructor. Methods called from the constructor should be private or final (no need to be both). By writing a setXXX() method, you are making it difficult to make the object immutable.
Campbell Ritchie wrote:You will have to alter the setPrice() method because you are calling a public method from the constructor. Methods called from the constructor should be private or final (no need to be both). By writing a setXXX() method, you are making it difficult to make the object immutable.
I'm not sure I understand could you give an example?
That prevents nasty surprises if anybody tries to override that method in a subclass.
Please space your code out more: one empty line between successive methods, please. Please also consider whether you need all those setXXX() methods, but setPrice() is the one you would want to retain if you retain any setXXX() methods at all.
Kevin O'Sullivan wrote:Could you catch it with a try/catch in your tester class? and if you can how would you do it?
At which point you realise that you should have used a more informative error message for your exception. As a general rule of thumb, you shouldn't catch unchecked exceptions, but this looks like a situation where that is a reasonable thing to do. There are much more elegant ways to create such Cars; the nextInt() method is overridden so as only to return values in a pre‑defined range, so you can avoid the exception altogether. I shall let you work out how the KeyboardInputs class works.