File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Need help correcting a mistake, array JAVA Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Need help correcting a mistake, array JAVA" Watch "Need help correcting a mistake, array JAVA" New topic

Need help correcting a mistake, array JAVA

Reem Akira

Joined: Dec 14, 2012
Posts: 6
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
Any suggestions?
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)
Avery Torres

Joined: Dec 15, 2012
Posts: 5
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.
Phil English
Ranch Hand

Joined: Jun 18, 2012
Posts: 62

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.
Reem Akira

Joined: Dec 14, 2012
Posts: 6
I solved it. I used a variable to keep track of how many strings were entered and use it in my loops. Thank you!
I agree. Here's the link:
subject: Need help correcting a mistake, array JAVA
It's not a secret anymore!