2017-08-05 99 views
0

的拷貝填充我想製作一個棋盤遊戲的移動版本,並且由於某種原因,我有一個ArrayList,其中所有元素都符合最後一個元素,只要添加一個新元素,我就可以不知道爲什麼。 (我非常新到Android工作室)Arraylist由最後一個元素Android Studio

下面是關心增加了列表中的所有類:

public class ScoreBoard { 
    private static final ScoreBoard ourInstance = new ScoreBoard(); 

    public static ScoreBoard getInstance() { 
     return ourInstance; 
    } 

    List<Player> Players; 
    int nrOfPlayers; 
    int activePlayer; 

    private ScoreBoard() { 
     Players = new ArrayList<Player>(); 
    } 

    public void addPlayer(CharSequence name) { 
     Player p = new Player(name); 
     Players.add(p); 
    } 

    public void nrOfPlayers(int number) 
    { 
     nrOfPlayers = number; 
    } 

    public boolean stop() 
    { 
     boolean stop = false; 

     if (nrOfPlayers <= Players.size()) 
     { 
      stop = true; 
     } 
     return stop; 
    } 

    public void StartGame() 
    { 
     Random random = new Random(); 
     random.nextInt(nrOfPlayers); 
    } 

    public CharSequence GetActivePlayerName() 
    { 
     return Players.get(activePlayer).name; 
    } 
} 

public class Player { 
    public CharSequence name; 
    public int points; 

    public Player(CharSequence name) 
    { 
     this.name = name; 
    } 
} 

public class PlayerName extends AppCompatActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_player_name); 
    } 

    public void addPlayer(View view) 
    { 
     ScoreBoard SB = ScoreBoard.getInstance(); 
     TextView nameText = (TextView)findViewById(R.id.NameText); 
     TextView playerText = (TextView)findViewById(R.id.PlayerText); 
     CharSequence name = nameText.getText(); 
     SB.addPlayer(name); 
     playerText.setText("Player " + (SB.Players.size() + 1) + " enter your name"); 
     Context context = getApplicationContext(); 
     int duration = Toast.LENGTH_SHORT; 

     Toast toast = Toast.makeText(context, name + " Added", duration); 
     toast.show(); 

     if(SB.stop()) 
     { 
      SB.StartGame(); 
      Intent intent = new Intent(this, TakeTurn.class); 
      startActivity(intent); 
     } 
     else 
     { 

     } 
    } 
} 
+0

你是什麼意思符合最後一個元素? –

+0

所有元素都成爲最後添加的元素的副本(應該有更好的措辭) – Calmaty

+0

「嗨,我看到你是新來的,如果你覺得答案可以解決問題,請點擊」接受「綠色的複選標記,這有助於將注意力集中在仍然沒有答案的舊版SO上 –

回答

0

您已經使用staticfinal同時初始化。刪除它們並修改你的記分卡類如下:

private ScoreBoard ourInstance = new ScoreBoard(); 

    public ScoreBoard getInstance() { 
     return ourInstance; 
    } 
+0

我不知道這是否能解決問題(必須對代碼進行一些更改以適應此問題),但如果我做了這個,我不能夠使用我的記分板類作爲一個單獨的類嗎? – Calmaty

+0

如果你聲明類的構造函數是私有的,那麼你可以有一個單例類,但是我不完全確定它。它的作品只是一個單獨的類。請參考這裏:http://www.java2novice.com/java_constructor_examples/singleton/ –