来自arraylist的两个对象的相同输出

时间:2013-04-24 03:53:15

标签: java arraylist tostring

class Use {
public static void main(String[] args) throws IOException {
    Use u = new Use();
    BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
    ArrayList<Square> sq = new ArrayList <Square>(); 
    int shapeChoice = 0;
    int customChoice = 0;
    int count = 0;
    String info1;
    boolean boolCase;
    System.out.println("Welcome, this program allows you to create and access    shapes, displaying the area and perimeter of each.");
    while (true){
        shapeChoice = Integer.parseInt(br.readLine());
        if (shapeChoice == 0) break;
        count++;
        sq.add(new Square(count, shapeChoice));
        String info = (sq.get(count-1).toString());
        System.out.println(info);
        if (count > 1) {
            info1 = (sq.get(count - 1).toString());
        System.out.println(info1);
        }
    }
    /*System.out.println("Enter Square Num");
    customChoice = Integer.parseInt(br.readLine());
    String info1 = (sq.get(customChoice - 1).toString());
    System.out.println(info1);*/
    for(int x = sq.size(); x > 0; x--){
        System.out.println(x);
        String info = (sq.get(x-1).toString());
        System.out.println(info);
    }       
}
}

abstract public class Test {
private static int s; //Base top
public Test(){
    s = 1;
}
Test(int s){
    this.s = s;
}
abstract public int findPerimeter();
abstract public int findArea();
public int getS() {
    return s;
}
public void setS(int s){
    this.s = s;
}

}

class Square extends Test{
private static int numSquares = 0;
private int iD;
public Square(int iD){
    super();
    numSquares ++;
}
public Square(int s, int iD){
    super(s);
    numSquares ++;
}
public int getID(){
    return iD;
}
public void setID(int iD){
    this.iD = iD;
}
public int getNumSquares(){
    return numSquares;
}
@Override
public int findArea(){
    return (super.getS()*super.getS());
}
@Override
public int findPerimeter() {
    return (super.getS())*4; 
}
public String toString(){
    return "Area is "+findArea()+" and Perimeter is "+findPerimeter();
}
public void decreaseNum(){
    numSquares --;
}
public int getS(){
    return super.getS();
}

}

My Test类创建一个正方形,我使用main来创建新的正方形,但是当我使用toString()方法在正方形上输出信息时,它只显示最近创建的对象的值

我怎样才能解决这个问题?

非常感谢阅读!

2 个答案:

答案 0 :(得分:0)

这可能是因为你在Test类中使用一个静态变量来存储我猜测的非静态变量“s”,这意味着它就是一面。检查实际上是否返回不同对象的最佳方法是将Object.hashcode附加到toString或根本不覆盖toString方法。

答案 1 :(得分:0)

 if (count > 1) {
            info1 = (sq.get(count - 1).toString());
 System.out.println(info1);

此行仅打印最后创建的Square。也许你想循环遍历数组?

编辑:

你在这里循环播放

for(int x = sq.size(); x > 0; x--){
        System.out.println(x);
        String info = (sq.get(x-1).toString());
        System.out.println(info);
    }  

但是这段代码永远不会执行,因为你处于while (true)

的无限循环中