Java Arrays:我想创建两个数组,每个数组包含3个int值

时间:2013-12-10 15:17:10

标签: java arrays oop

目的:  检索另一个类中Player类中定义的数组,以对数组内容执行其他操作;

到目前为止

代码:

public class Players {

//attributes

private int [] Player1 = new int [3];
private int [] Player2 = new int [3];
private int round=Math.random();

//Constructor

public Players(int [] p1, int [] p2 ){
[] player1 = [] p1
[] player2 = [] p2
}

问题规范:不编译;

5 个答案:

答案 0 :(得分:2)

您有多种语法以及类型不匹配问题

1) Java区分大小写

public Players(int [] p1, int [] p2 ){
 Player1 =  p1;
 Player1 =  p2;
}

所以

Player1 !=player1 

2)

[] player1 = [] p1

不是有效的java语法

3)最后Math.random()返回double,将其更改为

double random = Math.random();

答案 1 :(得分:1)

您必须通过逗号

分隔参数
public Game(int[] p1, int[] p2) {

这甚至没有接近工作(注意缺少分号):

[] player1 = [] p1
[] player2 = [] p2

您希望将实例字段设置为等于给定参数,但不需要重新定义它们是数组。

而是使用它:

this.player1 = p1;
this.player2 = p2;

请记住命名约定:字段以小写字母开头(因此player1代替Player1)。 Java区分大小写,因此Player1player1不一样。确切存在命名约定的原因之一。

最后:Math.random返回double。如果将它转换为int,你将失去其目的(它返回一个介于0和1之间的值,如果你将它转换为int,你将失去这两个边界之间的所有内容)。而是这样做:

private double round = Math.random();

答案 2 :(得分:1)

根据我的评论,您可能需要考虑像这样构建您的类:

public class Player {
    //attributes
    private int[] roundValues; 
    private double round=Math.random(); //not sure what you are using this for

    //Constructor
    public Player(int[] roundValues){
        this.roundValues = roundValues;
    }

    // use this to get the roundValues array
    public int[] getRoundValues() {
        return roundValues;
    }

    // use this to change the roundValues array
    public void setRoundValues(int[] roundValues) {
        this.roundValues = roundValues;
    }

    public static void main(String[] args) {
        int[] array1 = {1,2,3}; //just some dummy values
        Player player1 = new Player(array1); 
        // do this to get the player's round values
        int[] roundVals = player1.getRoundValues();
    }
}

答案 3 :(得分:0)

你的节目有几个错误。 检查以下一项:

public class Players {

    //attributes
    private int [] player1 = new int [3]; // use names with lowercase at beginning (convention)
    private int [] player2 = new int [3];
    private double round = Math.random();

    //Constructor
    public Players(int[] p1,  int[] p2) { // you missed a comma and a parenthesis
        player1 = p1; // no need to say again that they are arrays. add ';' at the end
        player2 = p2;
    } 

    // you could need to add these to access your private arrays from an other class
    public int[] getPlayer1(){
        return player1;
    }

    public int[] getPlayer2(){
        return player2;
    }
}

希望有所帮助

答案 4 :(得分:0)

  • 注意 player1 Player1 的区分大小写。
  • 添加一些分号
  • 删除一些用于设置数组变量的大括号
  • Math.random()方法返回一个double,而不是整数
  • 变量应以小写字母开头

像这样:

public class Players {

    //attributes

    private int[] player1 = new int[3];
    private int[] player2 = new int[3];
    private double round = Math.random();

    //Constructor

    public Players(int[] p1, int[] p2) {
        player1 = p1;
        player2 = p2;
    }
}