0

I created a class in a file called Pq which is an object having Strings like this

public class PQ {
    String ec;
    String com;
    String ai[3];
    String answers[3];
 }

Now I want to make an array of this object of length 10. Then fill each of the individual elements like ec,com with data as per my requirement with a for loop like

for(i=0;i<10;i++)
    pq.ec=25;

How to do this? I also want to fill ai,answers. How to access those elements I tried ArrayList but I am able to add the whole object but unable to add individual items Please help me out

1 Answer 1

3

In your PQ class define getters and setters to manipulate fields of your objects safely conforming to the principle of encapsulation.

public String getEc ()
{
    return ec;
}

public void setEc ( String ec )
{
    this.ec = ec;
}

public String getCom ()
{
    return com;
}

public void setCom ( String com )
{
    this.com = com;
}

public String [] getAi ()
{
    return ai;
}

public void setAi ( String [] ai )
{
    this.ai = ai;
}

public String [] getAnswers ()
{
    return answers;
}

public void setAnswers ( String [] answers )
{
    this.answers = answers;
}

To populate an array of PQ objects use a code similar to this:

PQ [] objects = new PQ [ 10 ];

for ( int i = 0; i < objects.length; i++ )
{
    objects [ i ].setEc( "your ec" );
    objects [ i ].setCom( "your com" );
    objects [ i ].setAi( new String [] {"fill the string array"} );
    objects [ i ].setAnswers( new String [] {"fill the string array"} );
}

Note that you can fill each field of individual objects by using the appropriate setter method and valid argument(s).

Sign up to request clarification or add additional context in comments.

4 Comments

@Chinnikrishna Using setter methods are not required as your Fields are not marked private, though it's recommended that you should mark your class variables private (or at least protected) and use setter methods to access them to respect encapsulation ;)
Might as well recommend adding a bunch of explicit constructors for instantiating/initializing pq.
@MH assuming the OP does that trivial assigning operations in constructor.
@deporter: Seen the phrasing of the question and the code snippet, I'm inclined to say so.

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.