Hello, this is me again with the same code, now working except for one part when I use the sentinel value it gives me a nullPointerExceptionError and I'm not quite sure what I need to change
Everything else works fine
Just when I enter "done" the error appears
If you don't know what I'm talking about, this is a program in which an user inputs a last name, and the last name should be returned with the following format ie "Smith " should be "T. H. Smith"
(takes last character , and takes the next to last and capitalizes them)
It looks like you are making an array of size 10, so it will never be able to hold more than 10 items(not sure if that is a problem or not).
What you need to do is have a variable that keeps track of how many items the user has added because right now your loop is trying to go through the entire array of size ten even if ten items have not been added.
Another thing you may want to think of is it track that the item being added is at least of size 2 and if it is smaller to either not use the value or return something like "A.A. A" AKA just repeat that one character instead of have a Index Out of Bounds Exception.
Your NPE stack trace will tell you exactly where you have a problem. When you initialise your string array with 10 elements each element is null until you replace that value. What happens when you access the tenth element if you only enter 9 elements into the array? Also, what happens if someone wants to enter 11 names?
You might want to consider an java.lang.ArrayList which is resizable. In this way you could choose to iterate over the ArrayList.size() or even define an iterator on the array. This would make your code much more flexible.
Joined: Dec 14, 2012
I solved it. I used a variable to keep track of how many strings were entered and use it in my loops. Thank you!