2013-10-23 1 views
1

Im new to java. 나는 왜 이런 오류가 발생하는지 이해하지 못한다. 각 객체를 저장하도록 배열리스트를 만들려고합니다. 오류가 발생했습니다. 식의 형식은 배열 형식이어야하지만 'newbug1 [i] .setspecies();'줄의 ArrayList로 확인됩니다. arraylists 사전표현식의 유형은 배열 유형이어야하지만

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

} 
+0

하위 배열을 사용하여'ArrayList' 요소에 액세스하지 않습니다. 'newbug1 [i]'는 배열에 사용됩니다. –

+0

'ArrayList! = Array' –

답변

2

에서

감사합니다 대신 get()를 사용

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

는 객체 참조를 저장하기 때문에 어떤 setFoo 호출은 ArrayList를에서 참조 원본 객체에 영향을 미칩니다.

2

ArrayList의 요소에 액세스하려면 get이라는 메서드를 사용해야합니다. 코드에서

, newbug1.get(i)

에 의해 newbug1[i]을 교체하고 또한, 당신은 또 다시 리콜 대신 변수에 해당 참조를 저장해야합니다

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

코드는 선명도 얻을 것입니다.

관련 문제