gpt4 book ai didi

java - 将方法返回值存储在 ArrayList 中

转载 作者:行者123 更新时间:2023-12-02 04:48:41 24 4
gpt4 key购买 nike

我正在编写一个程序来创建游戏板,并使用父类(super class)和子类来生成游戏板。本质上,我想使用一个 arrayList 来存储从 Cell 子类的方法返回的值。但我不知道该怎么做。我在 BoardGame 类中编写的内容给了我一个错误,我想不出其他方法来做到这一点。 GameBoard

import java.util.ArrayList;


public class BoardGame {



private Die theDie;



BoardGame(){





}

void buildBoard(){

ArrayList<Player> player;




Cell c = new Cell();

ArrayList<Cell>cells = new ArrayList<Cell>();

cells.add(c.landOn());

}

void runSimulation(){

}


int takeTurn(String n){

//since we don't know what we are returning yet
return 0;


}

String toString(String n){


//Since we aren't returning anything yet
return "Nothing";


}
}






public class Cell {

static int landOn(){


//Since we do not know what we are returning
return 0;
}

public String toString(){



//Since we do not know what we are returning
return "Blank";
}

}




public class Star extends Cell {

int landOn(){


//since we do not know what we are returning
return 5;
}

public String toString(){


//since we do not know what we are returning
return "Star: +5";
}

}



public class Lightning extends Cell {

int landOn(){


//since we do not know what we are returning
return -5;
}

public String toString(){


//since we do not know what we are returning
return "Lightning: -5";
}

}



public class X extends Cell {

int landOn(){


//since we do not know what we are returning
return -10;
}

public String toString(){


//since we do not know what we are returning
return "X: -10";
}

}



public class Smiley extends Cell {

int landOn(){


//since we do not know what we are returning
return 10;
}

public String toString(){


//since we do not know what we are returning
return "Smiley: +10";
}

}

最佳答案

您的ArrayList被声明为Cell您的方法的返回类型是int。您的 ArrayList 不能存储除 Cell 类型的实例之外的任何内容

要存储方法的所有返回类型,您需要一个Integer类型的ArrayList

使用 int 也不起作用,因为 int 是一个原语。

解决方案:

ArrayList<Integer> cells = new ArrayList<>();

关于java - 将方法返回值存储在 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29451754/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com