简体   繁体   中英

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


    }
}

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.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM