Whenever I try to run this nothing happens. Does anyone know what's wrong?

package hobbits;

public class Hobbits {

    String name;

    public static void main(String[] args) {

        Hobbits []h = new Hobbits[3];

        int z = 0;
        int x = 0;

        while (z < 4){
            h[z] = new Hobbits();
            if (z == 0){
                h[z].name = "bilbo";
            }
            if (z == 1){
                h[z].name = "frodo";
            }
            if (z == 2){
                h[z].name = "sam";
            }
            if (z == 3){
                h[z].name = "pippin";
            }
            z += 1;
        }

        while (x < 4){
            System.out.print(h[x].name + " is a ");
            System.out.println("good Hobbit name.");
            x += 1;
        }
    }

}

Recommended Answers

All 3 Replies

"Whenever I try to run this nothing happens. "
Wrong.
It throws an exception which you cannot ignore.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Hobbits.main(Hobbits.java:8)

h is an array of size 3, so valid index values are 0,1,2
On line 8 you try to access index 3

Setting your array size to 4 should solve your problems :)

Hobbits []h = new Hobbits[4];

h is an array of size 3, so valid index values are 0,1,2
On line 8 you try to access index 3

Sorry JamesCherrill, I didn't see you had posted that when I responded.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.