drake
drake

Reputation: 259

Holding multiple values at same index in array

My code retrieves a number of steps, then will output an instruction at each step via for loop. There will be a title, description, video, and audio. However, I am trying to think of a way to store each variable into a structure. This is what I came up with, but I don't think an array can store multiple values at the same index.

for(int i = 0; i < QRData.number_steps; i++){
        System.out.println("Inside for loop");
        array[i].setTitle(btn_instructions.get(i));
        array[i].setDescription(instruction_row.get(i));
        array[i].setInstructionVideo(videos.get(i));
        array[i].setAudioInstruction(audio.get(i));
}

What would be a better way to store these values, so that they are easy to retrieve later? I'm pretty sure my method doesn't work.

Upvotes: 0

Views: 6352

Answers (3)

Bardemantel
Bardemantel

Reputation: 26

You should create a Object like:

public class DataStorage{

  private String title;

  private String description;

  private File audioFile;

  private File videoFile;

  public DataStorage(String title, String description, File audioFile, File videoFile){
    this.title = title;
    this.description = description;
    this.audioFile = audioFile;
    this.videoFile = videoFile;
  }

  public String getTitle(){
    return this.title;
  }
 //similar for "description", "audioFile" and "videoFile"
 //...
}

For the DataStorage i would recommend using a ArrayList, because it is dynamic and you can add new elements while the Programm is running. Then you can save Data in there with the loop:

ArrayList<DataStorage> storage = new ArrayList<>();

for(int i = 0; i < QRData.number_steps; i++){
    storage.add(new DataStorage(btn_instructions.get(i),instruction_row.get(i),
    videos.get(i),audio.get(i));
}

This is a basic concept of object oriented Programming to define classes to store custom data.

You can now get the Data out of the Array by calling the "getters" of your Datastorage class. For example:

String title = storage.get(itemNumber).getTitle();

gives you the value of the "itemNumber" Title.

Upvotes: 1

You have to use objects arrays, using this you are going to create a class and an array of your class, for example check ne following code:

class Person{
private String name;
private Integer age;

Person(String name,Integer age){
     this.name=name;
     this.age=age;
}
----getters and setters methods-----

}

class Test{
public static void main(String args[]){
Person arr[]=new  Person[10];
arr[0]=new Person("Alex",26);
}
}

Check a complete example here http://www.java2s.com/Tutorial/Java/0200__Generics/ArraysStoringclassobjectsinArrayasdataitems.htm

Cheers

Upvotes: 0

Xion Dark
Xion Dark

Reputation: 3434

You should create a new object to store those values in, then store that object in the array.

Upvotes: 0

Related Questions