【问题标题】:Can't assign to first element in an array无法分配给数组中的第一个元素
【发布时间】:2014-06-05 18:39:08
【问题描述】:

由于某种原因,我无法为我创建的 int 数组中的第一个元素分配随机数。问题出在第 7 行:coord[0] = (int) (math.random() * numRows + 1); 我把错误贴在下面。

public class Ship {

int shipLength = 3;
int numRows = 5;

int[] coord = new int[shipLength];
coord[0] = (int) (math.random() * numRows + 1);

    for (int i=1;i<shipLength;i++){
        coord[i] = coord[i-1] + 1;
    }
    public setCoord(cell){
        coord[cell] = null;
    }

    public int[] getCoord(cell){
    return coord[[cell];
    }
} //class




C:\java\Battleship>javac Ship.java
Ship.java:7: ']' expected
coord[0] = (int) (math.random() * numRows + 1);
      ^
Ship.java:7: ';' expected
coord[0] = (int) (math.random() * numRows + 1);
       ^
Ship.java:7: illegal start of type
coord[0] = (int) (math.random() * numRows + 1);
         ^
Ship.java:7: <identifier> expected
coord[0] = (int) (math.random() * numRows + 1);
          ^

【问题讨论】:

  • 你认为代码应该在什么时候执行?类体有什么用?
  • 方法在哪里??你的代码结构不对
  • 我推荐你看一个基本的java教程。这是一个很好的教程:docs.oracle.com/javase/tutorial/java/index.html
  • 感谢 juan 的推荐,我现在实际上正在做一个教程,但速度有点慢,所以为了我自己的理智和娱乐,我试着超出了我在练习中被要求的内容。
  • @Sotirios 这是一个战舰游戏程序。这是在虚拟平面中以随机坐标创建战舰的类。

标签: java arrays assign


【解决方案1】:

您的代码失败的特定行是有效的代码行,但它需要在您的类的方法或构造函数中。

例如:

public class Ship {

    int shipLength = 3;
    int numRows = 5;

    int[] coord = new int[shipLength];
    public Ship() {
        coord[0] = (int) (Math.random() * numRows + 1);
        for (int i=1;i<shipLength;i++){
            coord[i] = coord[i-1] + 1;
        }
    }
    public void setCoord(int cell, int value){
        coord[cell] = value;
    }

    public int getCoord(int cell){
        return coord[cell];
    }
} 

【讨论】:

  • 它仍然无法编译——它充满了错误。 setCoord 方法没有返回类型,getCoord 方法应该返回一个 int,而它有一个太多 [
  • @user184994 抱歉,我进行了更新,我的第一次迭代只是将东西放入构造函数中。
  • 仍然需要更改getCoord的返回类型。 coord 变量是一个 int 数组,所以 coord[cell] 将返回一个 int :)
  • @user184994,是的;由于我的 IDE 尚未加载,因此正在通过眼睛进行更正。
  • 啊,好吧,所以除了将实例变量分配给文字之外,还需要构造函数。那讲得通。感谢您的帮助。
【解决方案2】:

public class Ship { 之后和public setCoord(cell){ 之前的代码都是类级别的,但它是分步代码,必须在构造函数、方法或实例初始化程序中。

还有其他几个基本错误。

也许:

public class Ship {
    int shipLength = 3;
    int numRows = 5;
    int[] coord;

    public Ship() {

        coord = new int[shipLength];
        coord[0] = (int) (Math.random() * numRows + 1);

        for (int i=1;i<shipLength;i++){
            coord[i] = coord[i-1] + 1;
        }
    }

    public void setCoord(int cell){
        coord[cell] = 0;
    }

    public int getCoord(int cell){
        return coord[cell];
    }
} //class

变化:

  1. 声明(和初始化器,虽然我更喜欢在构造函数中使用初始化器)放在类级别。

  2. 代码放入构造函数中。

  3. 去掉最后一个方法中多余的[

  4. 为各种方法返回值和参数添加缺少的类型。

  5. math 更改为Math

现在编译结果。我建议您查看与原始版本相比的更改,以便您了解各种问题。

【讨论】:

  • getCoord 方法应该返回一个 int
  • @user184994:不仅如此,代码充满了错误。
  • 是的 :) 我刚刚在另一条评论中提到了同样的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多