【问题标题】:Update Object in 2D Java Array更新二维 Java 数组中的对象
【发布时间】:2013-01-06 16:30:56
【问题描述】:

我目前有以下代码,我想用 X 更新 2D 数组中的特定位置,然后重新打印板。我目前被困在需要将数组中的对象更新为 X 的地方,但我不断收到:

Type mismatch: cannot convert from String to Ship

我做错了什么?我已经把所有的物体都放在了板上。

public void updateBoard(int row, int column, Ocean ocean){
    //get ship array
    Ship[][] sea = ocean.getShipArray();
    //mark the x/y co-ordinate with X 
    sea[row][column] = "X"; // PROBLEM  
    // print the board
}

我已经加入了船级

public abstract class Ship {
// TODO add appropriate comments
@Getter
private int size;
private String type;
private String shortForm;

// TODO add appropriate comments
@Getter
@Setter(AccessLevel.PACKAGE)
private int bowRow;
@Getter
@Setter(AccessLevel.PACKAGE)
private int bowColumn;
@Getter
@Setter(AccessLevel.PACKAGE)
private boolean horizontal;

/**
 * An array of boolean which indicates whether that part of the ship has
 * been hit. This is initialised by the appropriate sub-class. Battleships
 * use all 4 locations; cruisers use the first 3; destroyers 2; submarines
 * 1; and "empty sea" 1.
 */
protected boolean[] hit;


/**
 * clears the hit array indicating whether that part of the "Ship" has been
 * hit
 */
protected Ship(int size, String type, String shortForm) {
    this.size = size;
    this.setType(type);
    this.shortForm = shortForm;
    hit = new boolean[size];
    for (int i = 0; i < hit.length; i++)
        hit[i] = false;
}

/**
 * Checks that ship of this size will not overlap another ship, or touch
 * another ship (vertically, horizontally, or diagonally) and that ship will
 * not "stick out" beyond the array.
 * 
 * @param row
 *            that will contain the bow
 * @param column
 *            that will contain the bow
 * @param horizontal = true if horizontal
 * @param ocean
 * @return true if it is okay to put a ship of this size with its bow in
 *         this location, with the given orientation.
 */
public boolean okToPlaceShipAt(int row, int column, boolean horizontal,
        Ocean ocean) {
    // Try to catch exception error if ship goes past board
    try{
        Ship ships[][] = ocean.getShipArray();

        for (int i = 0; i < getSize(); i++){
        if (!(ships[row][column] instanceof EmptySea)){ 
        //  System.out.println("Cant Print here + " + row + column + getSize());
                return false;
        }else{
            if (horizontal) {
                column++; 
            } else {
                row++;  
            }
        //  System.out.print(ships[row][column]);

            }
    //  System.out.println(" ");

        }
        return true;
    }
    catch(Exception err){
    //  System.out.println("OMG an error");
        return false;
    } 



}

/**
 * "places" the ship in the ocean, assigning values to the bowRow,
 * bowColumn, and horizontal. Places a reference to the ship in the ships
 * array in the Ocean object.
 * 
 * @param row
 *            to contain the bow
 * @param column
 *            to contain the bow
 * @param horizontal
 * @param ocean
 */
public void placeShipAt(int row, int column, boolean horizontal, Ocean ocean) {

    this.setBowRow(row);
    this.setBowColumn(column);
    this.setHorizontal(horizontal);

    Ship ships[][] = ocean.getShipArray();

    for (int i = 0; i < getSize(); i++) {
        // set position in array to contain the ship
        ships[row][column] = this;
        if (horizontal) {
            column++;
        } else {
            row++;
        }
    }
}

private int getSize() {
    // TODO Auto-generated method stub
    return size;
}

private void setHorizontal(boolean horizontal2) {
    // TODO Auto-generated method stub
    horizontal = horizontal2;
}

private void setBowColumn(int column) {
    // TODO Auto-generated method stub
    bowColumn = column;
}

private void setBowRow(int row) {
    // TODO Auto-generated method stub
    bowRow = row;
}

/**
 * If this ship has been hit, marks that part of the ship as "hit"
 * 
 * @param row
 *            User's supplied row shot
 * @param column
 *            User's supplied column shot
 * @return true if ship is hit, false otherwise
 */
public boolean shootAt(int row, int column) {
    if ((isHorizontal() && (row != getBowRow()))
            || (!isHorizontal() && (column != getBowColumn())))
        return false; // it's not a hit

    // it's a hit. Work out offset & set that position in hit array to true
    hit[(row - getBowRow() + column - getBowColumn())] = true;

            return true;
}

private int getBowRow() {
    // TODO Auto-generated method stub
    return bowRow;
}

private int getBowColumn() {
    // TODO Auto-generated method stub
    return bowColumn;
}

private boolean isHorizontal() {
    // TODO Auto-generated method stub
    return false;
}

/**
 * checks whether this ship is sunk - using the hit array
 * 
 * @return true if every part of the ship has been hit, false otherwise.
 */
public boolean isSunk() {

    for (boolean b : hit)
        if (!b)
            return false;

    return true;
}


/**
 * @return a single character String to use in Ocean's print method
 */
@Override
public String toString() {
    return shortForm;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}
public String setHit(String hit){
    return hit;
}

}

有点长。 下面是扩展 Ship 类的船的示例,即 Submarine 类。除了尺寸之外,其他所有的都完全相同。

/*
 * A Battleship class which extends ship
 * Four Submarines in the game Length 1
 */
package Battleships;
public class Submarine extends Ship {
    private final static int SIZE = 1;
    /**
     * sets the length & clears the hit array
     */
    public Submarine() {
        super(SIZE, "Submarine", "S");
    }
}

【问题讨论】:

  • 错误说明你无法将String 对象转换为Ship 对象
  • 如果你用“X”表示一艘船,请使用字符串数组而不是船数组
  • getShipArray 实际上正在获取包含所有部件的电路板,我只是想用 X 替换一个部件。我希望这能解释更多。
  • 嗯,从类声明器public abstract class Ship 可以看出,我们不能直接创建Ships。 (abstract 类不能直接实例化)。我们现在要做的是找到哪些类extend Ship,因为那些将是我们实际可以创建的类。基于此评论Battleships use all 4 locations; cruisers use the first 3; destroyers 2; submarines 1; and "empty sea" 1. 我猜有些文件的名称与Battleship, Submarine, Cruiser, and Destroyer 类似?如果是这样,您还可以为其中之一发布构造函数吗?我们将需要它们。
  • 其实还有一个问题。你想用这行你的原始代码做什么//mark the x/y co-ordinate with X sea[row][column] = "X"; // PROBLEM你在(行,列)开枪吗?试图在那里放置一艘船?

标签: java arrays compiler-errors type-mismatch


【解决方案1】:

seaShip[][]"X"String。您不能将String 放在包含Ship 的变量中。

编辑:

由于您尝试射击一艘船,而不是放置一艘新船,我怀疑您真正需要的是使用船的以下功能......

public boolean shootAt(int row, int column).

从 Ship 的代码中,我猜你真正需要做的是......

sea[row][column].shootAt(row,column);

【讨论】:

  • 好的,但是我如何将当前有“S”的sea[row][column] 的值更改为“X”,记住“S”是我放置在那个位置的对象sea[row][column]。据我了解,它是一个对象 Ship,与 String、Char 或 int 相对应。
  • 你需要创建一个Xship 对象。将Ship(尤其是构造函数)的源代码添加到您的问题中,否则我们不知道它是什么或它们是如何构造的。
【解决方案2】:

只需创建一艘特殊船,让它代表一个“X”。根据您更新的问题,您可以按如下方式创建新船:

sea[row][column] = new Ship(1,"Cthulu","X");

现在,无论何时打印 Ship,您都会看到一个“X”,因为 Ship 类的 toString() 方法返回的是 shortForm 字符串值。

您还可以使用自己的 toString() 方法扩展 Ship 类,以便拥有一种真正不同表示 X 的船。

【讨论】:

  • 这不能作为一个答案,因为到目前为止你还不知道 Ship 类的结构。它可能没有您指定类型的构造函数。
  • 构造函数很可能不正确。但是上面列出了他可以做些什么来解决他的问题的基本想法。理想情况下,在 Ship 类/扩展 Ship 的类中有一个静态变量,表示 X。
  • 上面的例子给了我一个“无法实例化类型 Ship”的错误。海里已经有了 Ships,它们扩展了 Ship 类。我只是想将二维数组中的值替换为字符“X”或字符串“X”。
  • 一组船舶只能包含其他船舶。这是我们大家必须遵守的基本规则。因此,您需要创建一个代表 X 的假船,否则您需要更改整个程序。
  • 您可以创建另一个扩展 Ship 的对象,并在其 toString() 方法中打印出一个“X”?这是您遇到的一个非常简单的问题,有多种解决方法。
猜你喜欢
  • 2014-04-11
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多