0

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?

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
dan
  • 127
  • 9
  • 1
    What can *this* be for??? Who would use an old plain Java array for such a purpose? Consider using `List` instead! – Honza Zidek Jul 02 '15 at 16:37

3 Answers3

4

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);
  }
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0
class RecordOfStudent{
    String[] record_value;
    if((name!=null))&&(credit!=null)){
        String record=name+credit;
        record_value={record};
    }
}

Hope this will help you

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
0

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?

Community
  • 1
  • 1
LucyMarieJ
  • 132
  • 1
  • 7