I'm starting with java, and I need to create a method for my first program.
What I have to do is this: I create Strings one by one, and I save them on a String[] array. These strings have this structure:
String = word1 word2 word3 code;
Then, when I want, I can list them showing the entire array on the console. And also, if I want, I can delete one specific string from the array.
To achieve this, I'm using the code that I asign to each array. This code is generated each time I add one String to the array, so this code matches with the position that the string has in the array.
When I want to delete one String, I have to pass to the method the code of the string. In this case, the code is the same as the position of the string, so when I pass the code, actually what I'm passing is the position.
The first time I delete a String this works, but the second time fails because of this. Lets suppose we've got:
String0 = word1 word2 word3 0
String1 = word4 word5 word6 1
String2 = word7 word8 word9 2
If I delete String1, now the array is resized to 2 Strings (0 and 1), so when I add a new String, it will reasing the code 2 to this new String, so I will have:
String0 = word1 word2 word3 0
String2 = word7 word8 word9 2
String3 = word10 word11 word12 2
This all is caused because to asign the code to the string, I use the position of the String in the array. So, what will the best way to have this functionality but in a correct way?
This is my code:
I add a string to the array this way in the main:
musicList.add(new Music(title, autor, format, code));
I list the array on the console this way:
System.out.println(musicList.toString());
And I delete it this way:
musicList.delete(code);
The methods add(), toString() and delete() are custom methods that I've defined in other class this way:
public void add(Music m){
musicList[pos_counter] = m;
pos_counter++;
}
public void delete(int code){
Music[] tempMusic = new Music[musicList.length];
int index_1 = 0;
for (int i=0; i<musicList.length; i++){
if(i != code){
tempMusic[index_1] = musicList[i];
index_1++;
}
}
int index_2 = 0;
for (int i=0; i<tempMusic.length; i++){
musicList[index_2] = tempMusic[i];
index_2++;
}
pos_counter--;
}
The toString() method simply shows the instance in a String way.
Thes Music[] instance just calls to other class where is defined a constructor with the elements of the Music List (these are title, autor, format or type and code):
public Music(String title, String autor, String type, int code){
this.setTitle(title);
this.setAutor(autor);
this.setType(type);
this.setCode(code);
}