表达式的类型必须是数组类型,但它解析为

时间:2013-10-23 14:17:53

标签: java arrays arraylist

我是java新手。我不明白为什么会发生这些错误。尝试创建一个数组列表,以便保存每个对象。我得到的错误是表达式的类型必须是数组类型,但它解析为'newbug1 [i] .setspecies();'

行上的ArrayList

提前谢谢

import javax.swing.JOptionPane;
import java.util.ArrayList;

public class Abug2 {
    private String species;
    private String name;
    private char symbol = '\0'; 
    private int horposition = 0, verposition = 0, energy = 0, uniqueID = 1, counter; 


    public Abug2(String species, String name, char symbol)
    {
        uniqueID = counter;
        counter++;
    }


    public void setspecies(){
    species = JOptionPane.showInputDialog(null, "Enter the species: ");
    }
    public String getspecies(){
        return species;
    }

    public void setname(){
    name = JOptionPane.showInputDialog(null, "Enter the name: ");
    }
    public String getname(){
    return name;
    }

    public void setsymbol(){
    symbol = name.charAt(0);
    }
    public char getsymbol(){
        return symbol;
    }

    public int getid(){
        return uniqueID;
    }

    public int gethorizontal(){
    return horposition;
    }

    public int getvertical(){ 
        return verposition;
    }

    public int getenergy(){
        return energy;
    }

    //The class ABug has a set of methods: two or more constructors, toString, toText, and getters and setters for the attributes 

    public String toString(){
        String tostring = "\nName: " + name + "\nHorizontal Position: " + horposition + "\nVertical Position: " + verposition + "\n";
                return tostring;
    }

    public String toText(){
        String totext = getspecies() + getname() + getsymbol() + getid() + gethorizontal() + getvertical() + getenergy();
                return totext;
    }


    public static void main (String [] args){       

        ArrayList<Abug2> newbug1 = new ArrayList<Abug2>();

        String choice = JOptionPane.showInputDialog(null, "Would you like to add another bug?: ");
            do{for (int i = 0; i < 3; i++) {

                newbug1.add(new Abug2("Bug", "Spider", 's'));

                newbug1[i].setspecies();
                newbug1[i].setname();
                newbug1[i].setsymbol();

                System.out.println(newbug1[i].toString());

            }       }while(choice != "yes");
            }

}

2 个答案:

答案 0 :(得分:2)

对于arraylists而言使用get()代替:

newbug1.get(i).setspecies();
newbug1.get(i).setname();
newbug1.get(i).setsymbol();

因为它存储对象引用,所以任何setFoo调用都会影响arraylist中引用的原始对象。

答案 1 :(得分:2)

要访问ArrayList中的元素,您必须使用名为get的方法。

在您的代码中,将newbug1[i]替换为newbug1.get(i)

此外,您应该将该引用存储在变量中,而不是一次又一次地重新调用它:

Abug2 currentBug = newbug1.get(i);
currentBug.setSpecies();   

您的代码将获得清晰度。