2017-05-28 149 views
-6

从来就清除本身一直奉行通过继承和抽象类,但我有相当使用构造和一个ArrayList一些麻烦。的ArrayList在每次迭代

每次我咨询我的所有的信息已添加到我的ArrayList中,他们似乎只打印最近添加的元素,这是我走到这一步......

public static void main(String[] args) throws IOException { 
do{ 
switch(menu){ 
case 1: 
int x=//random generated number; 
String name=//insert name; 
reception add=new Reception(x,name);continue; 


Public class reception extends Hotel{ 
public Reception(int number,String name,){ 
super(number,name); 
} 

import java.util.ArrayList; 

public abstract class Hotel { 
    ArrayList<Integer> numerodehotel = new ArrayList<Integer>(); 
    ArrayList<String> residente1 = new ArrayList<String>(); 


    public Hotel(int number, String resident){ 
    this.resident1.add(resident); 
    this.hotelroomnumber.add(number); 
    } 

每次我尝试打印所有元素他们只似乎表明在这两个ArrayList中,最后添加的元素,几乎就像是正在重置自己在每次迭代。

在主类有一个做一个开关,同时,我的想法是应该添加的所有投入要素没有resseting并能够征询他们的意见都

+1

请你至少后一些代码,编译* *? – QBrute

+0

继续而不是休息是否正常?在开关?与继续创建时(true)循环,这是正常的,nothirg appnes是 –

+1

后请格式化该字迹模糊混乱。 – EJP

回答

0

您创建一个新的接收的每个周期迭代对象。尝试在循环之前放置此定义并在循环中使用此对象。此外,你需要写一个空的构造函数和getter/setter方法值:

reception add=new Reception(); 
do { 
    ... 
    add.setNumerodehotel(x); 
    add.setResidente1(name); 
} while (...) 

public abstract class Hotel { 
    ArrayList<Integer> numerodehotel = new ArrayList<Integer>(); 
    ArrayList<String> residente1 = new ArrayList<String>(); 

    public Hotel(){ 
    } 

    public void setNumerodehotel(int number){ 
     this.hotelroomnumber.add(number); 
    } 

    public void setResidente1(String resident){ 
     this.resident1.add(resident); 
    } 
} 
0

的缺陷是你的Hotel类的构造函数中。您在施工Hotel类的定义ArrayLists

public abstract class Hotel { 
    // Every time you create a new Hotel these two lines are executed 
    ArrayList<Integer> numerodehotel = new ArrayList<Integer>(); 
    ArrayList<String> residente1 = new ArrayList<String>(); 

    public Hotel(int number, String resident){ 
     this.resident1.add(resident); 
     this.hotelroomnumber.add(number); 
    } 
} 

这类似于这样算下来

public abstract class Hotel { 
    ArrayList<Integer> numerodehotel; 
    ArrayList<String> residente1; 

    public Hotel(int number, String resident){ 
     numerodehotel = new ArrayList<Integer>(); 
     residente1 = new ArrayList<String>(); 
     this.resident1.add(resident); 
     this.hotelroomnumber.add(number); 

    } 
} 

,你可以看到,每次创建一个Reception(新Hotel),一新的ArrayList被创建,然后只有一个项目将永远存在您的ArrayLists

您可能只想从构造函数中删除添加并通过单独的方法添加。