0

I am just getting started with OOP, and I am trying to create a program that creates an array to store three different types of information, a name, double and an Int.

For some reason, when I run the program and enter the information, it is not stored properly. If I enter, for example, "James", 22.5, 4 on iteration 1, then "John", 23.66, 8 on iteration 2, then print the array, john, 23.66 and 8 prints out twice. I want each iteration of i in my array to store a different set of values, in essence, but I can't seem to figure out why that is not working.

*EDIT TO REFLECT ANSWER

for(int i=0; i<boats.length; i++) {
    System.out.printf("Name: " + boats[i].getName(name) + "  " +
                       "Age: " + boats[i].getLength(length) + "  " +
                       "Length: " + boats[i].getRating(rating) + "\n\n");
}
in.close();

** Code for class

Public Class file
    public String getName(String name) {
        return name;
    }

    public double getLength(double length) {
        return length;
    }

    public int getRating(int rating) {
        return rating;
    }
1

1 Answer 1

5

Your getters are returning the parameter you are passing in, not the value stored by the setter.

The values in the variables you are passing as the parameters are the last values you input, so you will always print the last values you input.

Remove the parameter from the getter.

public String getName() {
    return name;
}

And invoke like

boats[i].getName()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! That works perfectly and your explanation helped me understand what I did wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.