如何在构造函数类中实例化和操作数组(以及一般的变量)

时间:2015-10-05 00:38:25

标签: java arrays constructor

http://pastebin.com/xBqdUtTg - 主要 http://pastebin.com/BadasC7N - 构造函数

我必须在构造函数文件中创建一个方法,将一个播放器添加到一个数组中,但是我不允许更改上面项目中给出的代码片段。我的问题是我不知道如何使用通过用户输入给出的正确大小来实例化数组,因为我必须坚持使用addAPlayer(String playername)的框架并且不能添加参数决定长度。另外,我不知道如何在构造函数中操作变量

   -m, --monitor
          Instead of exiting  after  receiving  a  single  event,  execute
          indefinitely.   The default behaviour is to exit after the first
          event occurs.

这不起作用,所以我还有什么方法可以操纵这些变量?在我为家庭作业提供的存根代码中有类变量,但它们被标记为私有,所以我不能直接更改它们,并且已经给出了构造函数的参数,所以我不能在那里定义它们

编辑:主文件中的for循环也会在每次进行时调用方法addAPlayer,以便设置通过用户输入输入的正确数量的播放器名称,但是如何确保每次调用时该方法设置数组的不同索引等于名称

编辑:

public class Practice{
    public Practice(){
        int x;
        int y;
    }
    public static void main(String[] args){
        Practice prac = new Practice();
        prac.x = 1;
        prac.y = 2;
    }
}

^^^构造函数类

    public class NBATeam {
    private String sTeamName;
    private int nWin;
    private int nLoss;
    private String [] playerArray;
    //Your code here

    }//end of class definition

1 个答案:

答案 0 :(得分:0)

除非你知道你要添加多少名球员,否则不要创建NBA球队的实例。这都是假设您无法使用List<>。

int currentIndex;
public NBATeam(String name, int numberOfPlayers) {
    sTeamName = name;
    playerArray = new String[numberOfPlayers];
}
public void addAPlayer(String playerName) {
    playerArray[currentIndex] = playerName;
    currentIndex++;
}

然后在课程NBATeam中添加:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bongkorr/com.hospifinder.Maps}: java.lang.NullPointerException: CameraUpdateFactory is not initialized

同样,这有点容易出错,因为你应该检查是否经常调用addAPlayer。你还需要考虑playerArray没有完全填充等。 您还需要检查传递给ctor的numberOfPlayers是否是有效值等等。

最好使用List<>为此,但由于您必须在示例代码中使用该数组,您必须添加所有这些检查(作为练习留给读者)