为什么这个对象数组中的每个元素得到由过去的对象覆盖? [英] Why does each element in this array of objects get overwritten by the last object?

查看:132
本文介绍了为什么这个对象数组中的每个元素得到由过去的对象覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

public static void main(String[] args) {
  Player players[] = new Player[2];
  Scanner kb = new Scanner(System.in);
  System.out.println("Enter Player 1's name");
  players[0] = new Player(kb.nextLine());
  System.out.println("Enter Player 2's name");
  players[1] = new Player(kb.nextLine());
  System.out.println("Welcome "+ players[0].getName() + " and " + players[1].getName());    
}

其目的是创造一个新的选手对象并存储游戏者的姓名,同时保持在阵列中的所有对象。

It is meant to create a new player object and store the name of the player, while keeping all the objects in the array.

下面是玩家等级:

public class Player {
  static String name;
  public Player(String playerName) {
    name = playerName;
  }

  public String getName(){
    return name;
  } 
}

什么实际情况是,当我刚刚有1对象它的工作原理,但是当我有2个,阵列中的每个元素都是一样的第二位。当我有数组中3个对象,每个元件是一样的第三等

What actually happens is that it works when I just have 1 object, but when I have 2, each element in the array is the same as the second. When I have 3 objects in the array, each element is the same as the 3rd, etc.

我不知道为什么发生这种情况,或如何纠正它,而且它已经莫名其妙我小时:/

I'm not sure why this is happening, or how to correct it, and it's been baffling me for hours :/

推荐答案

由于静电场的启示。静跨对象实例使用。它们存储在一流水平。

Its because of the static field. Statics are used across object instances. They are stored at class level.

下面code将工作:

class Player
{
    String name;

    public Player(String playerName)
    {
        name = playerName;
    }

    public String getName()
    {
        return name;
    }
}

这篇关于为什么这个对象数组中的每个元素得到由过去的对象覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆