首页 > 解决方案 > 如何打印出一组对象

问题描述

所以我正在制作一个游戏并有一个类 Players 每个玩家都有一个namescore

我试图通过调用一个函数并使用 for 循环并根据用户的用户输入设置玩家名称来获取每个 Player 对象名称的用户输入。

我在研究时尝试了一些东西,但我仍然有问题。

我看到有人说这Array.toString(arr)就是打印对象数组的方式。

我现在收到一个错误

.\Player.java:13: error: incompatible types: unexpected return value
                return "Player: " + name + "      Score"  + score;
import java.util.*;
class diceGame{
    // calling main method
    public static void main (String[] args){
        createPlayersArray(); 

    }

    //Get the details oto launch game such as the number of players
    //and collects their names to store in a array
    public static void createPlayersArray () {
        Scanner kb = new Scanner(System.in);


        System.out.println("Please enter the number of players: ");
        int numOfPlayers = kb.nextInt();
        //Player array to hold all the players
        Player [] playerArray = new Player[numOfPlayers];


        //Array to set the players names
        for (int i = 0; i < numOfPlayers; i ++ ) {

            System.out.println("Please enter your name: ");
            String currentPlayerName = kb.next();
            playerArray[i] = new Player(currentPlayerName, 0);

         }

         System.out.println("This should be the list of players");
         for (int i = 0; i < playerArray.length; i ++ ) { 
                System.out.println(Array.toString(playerArray));
         }

    };
}

/////////////////////// Player Class//////////////////////////

class Player{
    public String name;
    public int score;



    public Player (String n, int s){
        name = n;
        score = s;
    }

    public void nameAndScore (){
        return "Player: " + name + "      Score"  + score;
    }


    //Geters and Setter name 
    public String getName(){
        return name;
    };

    public void setName(){
        return name;
    }
};

这不是一个错误,但我正在显示内存地址:

Player@880ec60
Player@3f3afe78
Player@7f63425a
Player@36d64342

我希望控制台打印:

Tom   score: 0
Jerry score: 0

标签: java

解决方案


推荐阅读