当前位置: 动力学知识库 > 问答 > 编程问答 >

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..

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();

}

}

网友答案:

In your object define your setters and getters (in this case specifically the getName)

String name = spillerne.get(i).getName();
System.out.print("This is the player name: "+name);
网友答案:

You are getting the Player object out of the ArrayList, so just ask it for its name:

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.

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.");
分享给朋友:
您可能感兴趣的文章:
随机阅读: