[英]How to get one value of an object from only knowing the index ArrayList, Java?
I have created an Arraylist of players for a simple game. 我为一个简单的游戏创建了一个玩家列表。 I need to display in the console whos turn it is to play.
我需要在控制台中显示轮到谁玩。 I have a class "Player" where I store name and score.
我有一个“玩家”类,用于存储名称和分数。 Also a constructor that defines these values for each player.
也是为每个玩家定义这些值的构造函数。 Can't figure out how to get only the name of a player from the index in the Arraylist..
无法弄清楚如何仅从Arraylist的索引中获取播放器的名称。
package Øving5;
import java.util.ArrayList;
import java.util.Scanner;
public class Game {
public static void Round() {
ArrayList<Player> players = new ArrayList<Player>();
Scanner in = new Scanner(System.in);
System.out.print("Write down the number of players: ");
int numplayers = in.nextInt();
for (int i = 0; i < numplayers; i++)
players.add(new Player());
for (int i = 0; i < numplayers; i++)
theplayer = players.get(i); // Don't know what to do here..
System.out.print("It is " + toString(theplayer) + "'s turn.");
}
public static void main(String[] args) {
Round();
}
}
You are getting the Player
object out of the ArrayList
, so just ask it for its name: 您正在从
ArrayList
中获取Player
对象,因此只需询问其名称即可:
for( Player p : players) {
System.out.println(p.getName());
}
Here I assume that your player class has a getName()
method which returns the player's name. 在这里,我假设您的播放器类具有一个
getName()
方法,该方法返回播放器的名称。
Similarly you can print the name of a player at a particular index: 同样,您可以在特定索引处打印播放器的名称:
System.out.println(players.get(2).getName());
First of all you are not adding any information to your player class. 首先,您不会在播放器类中添加任何信息。
For each player you do 对于每个玩家
spillerne.add(new Player());
It is just creating an empty class. 它只是创建一个空类。 You have to create a class player more or less like this
您必须像这样大致创建一个班级播放器
class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String getName() {
return this.name
}
Then your code becomes 然后你的代码变成
for (int i=0; i<numplayers; i++)
spillerne.add(new Player("Player " + i)); // Here you can also use user input. This is just an example of giving a name
for (int i=0; i<numplayers; i++)
System.out.print("Det er "+ spillerne.get(i).getName + "sin tur.");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.