音乐椅。音乐椅是一种儿童游戏,玩家可以在一组椅子上走动,同时播放一些音乐。当音乐停止时,每个人都必须坐下来。但是,有一把椅子比有人少,所以有人被排除在外。事实上,那个人已经退出游戏。椅子被移除了。并且游戏再次播放;别人出去了。这种情况一直持续到只剩下一名球员为胜者。
我在播放器[]
中存储命令行参数时遇到问题这是我的代码
import java.util.*;
public class MusicalChairs {
Player [] players;
Random r = new Random();
public static void main(String[] args){
MusicalChairs mc = new MusicalChairs();
mc.setUpGame(args);
}
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
}
}
public void showStatus(){
}
public void winner(){
System.out.println("is the winner");
}
}
class Player{
enum Status{IN,OUT};
private String name;
private Status status;
public Player(String n){
name=n;
}
public String getName(){
return name;
}
public void setStatus(Status s){
status=s;
}
public Status getStatus(){
return status;
}
public String toString(){
String ret = name;
if(status==Status.IN){
ret="IN ";
}
else{
ret="OUT ";
}
return ret;
}
}
答案 0 :(得分:1)
您没有在数组中存储参数。如果您的问题如何操作,那么您应该:
players
数组。Player
对象并将其存储在数组中。这可以这样做:
public void setUpGame(String [] p) {
System.out.println("This is how we stand.......");
//Initialize the `players` array.
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
//For each argument, you must create a `Player` object and store it in the array.
players[i] = new Player(p[i]);
players[i].setStatus(Status.IN);
}
//Once your array is filled, use the data in your program.
//...
}
问题仍然存在:您的具体问题是什么?
答案 1 :(得分:1)
我认为您需要更新代码以创建新的播放器并在阵列中维护引用...
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
// You may want to check for a 0 number of players...
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
players[i] = new Player(p[i]);
players[i].setStatus(Player.Status.IN);
System.out.println(players[i].getName()+" is "+ players[i].getStatus());
}
}