dan
dan

Reputation: 127

How can I create an array(s) that only add to the list if a condition is met

How can I create an arrays that tracks student names and their corresponding credits, but only adds the student information(i.e. name + credits) to the array if only a certain condition is met?

Upvotes: 0

Views: 79

Answers (3)

LucyMarieJ
LucyMarieJ

Reputation: 132

Assuming you have an object, here I called it StudentRecord, that contains the information on the name and credit, the following would work in your main:

StudentRecord records = new StudentRecord[numStudents]; //numstudents set ahead of time
if(condition){  //such as (currRecord.credits == 90) 
    records[count] = currRecord;  //currRecord is the record you are testing
}

This would work, but you would have to constantly reallocate the array if you didn't know your size in advance. ArrayLists really would work better.

If you must use arrays, however, this question will help: Java dynamic array sizes?

Upvotes: 0

Kunal Kumar
Kunal Kumar

Reputation: 1

class RecordOfStudent{
    String[] record_value;
    if((name!=null))&&(credit!=null)){
        String record=name+credit;
        record_value={record};
    }
}

Hope this will help you

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 26981

You can extend Arraylist and override the add() method:

public class ConditionalArrayList extends ArrayList<Object> {
  @Override
  public boolean add(Object e) {
    if (condition)
        return super.add(e);
  }
}

Upvotes: 4

Related Questions