java - 如何打印出一组对象
问题描述
所以我正在制作一个游戏并有一个类 Players 每个玩家都有一个name
和score
。
我试图通过调用一个函数并使用 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
解决方案
推荐阅读
- c# - 排序并打印 2 个元素的列表,而不将排序后的版本保存在另一个列表中
- java - 一个组件需要一个名为“dataSource”的 bean,但找不到该 bean
- android - Android Studio:'adb' 不是内部或外部命令、可运行程序或批处理文件
- java - 如何让消息出现在不同的侧面?
- c - 将 Void* LinkedList 节点与 C 中的字符串进行比较
- java - 我如何从枚举中选择随机值?
- typescript - 从时间戳转换为日期与本地主机和服务器不同
- javascript - 单击没有按钮 ID 或类的 javascript 中的按钮
- java - 使用 StAX 写入现有 xml 文件
- c++ - 如何检查程序员在 C++ 中提供的两种不同格式的输入