Could someone please have a look at my code and point out where I'm going wrong?
It compiles fine, but when I run it, I only get the expected output ("I like this food.") for the first element in the food array, "carrot". If I try to pass any of the other listed strings, "burgers", "rice" or "pizza", I get caught by the exception.
What is happening is you are checking whether ONLY the first element of the array is a particular type of food BEFORE throwing an exception. If you have typed in "carrot" then the carrot is in fact the first element of the array so we have a good match hence the code breaks out of the LOOP. If the food you have typed in is "BURGERS" for example your code checks whether the first element of the array is "burgers" (first LOOP iteration). If it is you will get a correct response but if it is not you will get the EXCEPTION IN THE FIRST LOOP ITERATION. You never get to the second, third and so on because you are throwing the exception if the first command line argument is not the same as the first element of the array.
One way to fix that is to use a while loop and a boolean variable acting like a flag...Something from this sort:
I have tried to code many different ways follow the way you coded, but it won't work. A better approach is have the "new BadFoodException()" out side the for loop like other have proposed, if it found it will print and return to the for loop, otherwise exit the for loop which will throw an exception.
Here is the complete solution, you can test and verify. Hope this help...
"Your life is in your hands, to make of it what you choose."
Hello Guys, since we will need to know about the 'Console' class for the exams, I decided to experiment and modify Chandela's program since it has to do with reading user inputs and getting useful information out of the inputs and it worked perfectly! and made it possible to enter arguments as much as you like.
I decided to share it with you all. Please let me know if you have doubts, I'll try and clarify the doubts:
In Your Pursuit Towards Certification, NEVER Give Up.
Joined: Apr 13, 2011
Jacob's Console input is works perfectly..Scanner can be use as well if we want to find stuffs or tokenizaing data, I'd say a more versatile approach of getting input, use of Regex and tokenizing data. Haven't try it yet, but will try and see how it works...
Joined: Feb 18, 2011
Tommy, your enhanced for-loop suggestion works perfectly as well. That's how I originally thought of coding mine, but because I was having problems, I ended up changing it to a normal for-loop.
Not that it ever made a difference, the problem was with the break on line 38, as well has having the exception as an else clause. Much better to have the exception outside the for-loop, bypassing it with a return statement if a match is found.
Ikpefua, thanks for your input. I haven't got to that part yet though I promise I will have a look at your code when I get to the relevant chapters in my book. Cheers!