1

我是 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");
            }

}
4

2 回答 2

2

对于数组列表,请get()改用:

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

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

于 2013-10-23T14:19:14.623 回答
2

为了访问 ArrayList 中的元素,您必须使用一个名为get.

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

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

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

您的代码将变得更加清晰。

于 2013-10-23T14:20:46.343 回答