数组必需,但ArrayList< String>发现 [英] array required, but ArrayList<String> found

查看:989
本文介绍了数组必需,但ArrayList< String>发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个红宝石背景,我是新手java,我写了一个基本的程序,但不知怎的,我得到一个错误,我无法修复!我的代码:

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]);


推荐答案

你需要使用 get() 方法从 ArrayList 获取特定索引处的元素。你不能使用 [] 来获取arraylist中特定索引处的元素。它只适用于数组,而文件不是数组,而是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.

System.out.println( i + ". Ist: " + files.get(i));

此外,循环的条件有点偏。 files.size()< = i false ,因此,它不会输入 for 循环。

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.

将其改为这样的。

for(int i = 0; i < files.size() ; i++){

这篇关于数组必需,但ArrayList&lt; String&gt;发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆