I have a ruby backround and im new to java i wrote a basic programm but somehow i get a error i cant fix! My code:
import java.util.ArrayList;
public class Music {
private ArrayList<String> files;
public static void main(String args[]){
Music a = new Music();
a.addFile("Chasen Paper");
a.addFile("Mama");
a.addFile("Hell Yes");
a.removeFile("Hell Yes");
}
public Music(){
files = new ArrayList<String>();
}
public void addFile(String filename){
files.add(filename);
}
public void returnFiles(){
for(int i = 0; files.size() <= i; i++){
System.out.println( i + ". Ist: " + files[i]);
}
}
public void removeFile(String filename){
System.out.println("Vorher gab es " + files.size() + " Dateien");
files.remove(filename);
System.out.println("Jetzt gibt es " + files.size() + " Dateien");
}
}
When i try to compile it i get somehow this error: What did i wrong? Thanks!
Music.java:26: error: array required, but ArrayList<String> found
System.out.println( i + ". Ist: " + files[i]);
Last Updated : 11 Dec, 2018 We have discussed that an array of ArrayList is not possible without warning. A better idea is to use ArrayList of ArrayList.
You need to use the get () method to get the element at a particular index from an ArrayList. You can't use [] to get the element at a particular index, in an arraylist. Its possible only for arrays and your files is not an array, but an ArrayList.
A better idea is to use ArrayList of ArrayList. Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
They do have a length field however. And since the error message you speak of was something other than what would have been produced in the above, I have to conclude that studentClasses is indeed a String, not an array. ... equals (studentClasses [ i ]) ...
You need to use the get()
method to get the element at a particular index from an ArrayList
. You can't use []
to get the element at a particular index, in an arraylist. Its possible only for arrays and your files
is not an array, but an ArrayList.
System.out.println( i + ". Ist: " + files.get(i));
Also, the condition in your for
loop is a bit off. files.size() <= i
is false
, and therefore, it doesn't enter the for
loop at all.
Change it to something like this.
for(int i = 0; i < files.size() ; i++){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With