方法 public boolean mergesWith(Tile moving)
返回 true
如果 this
和 moving
瓷砖具有相同的值(value)。但是当我通过执行以下操作检查它们是否相同时:
if(this.value == temp.value){
return true;
}
然后它向我显示关于 temp.value
的错误,说 value cannot be resolved or is not a field。
我该如何解决?
TwoNTile类:
package Game2048;
// Concrete implementation of a Tile. TwoNTiles merge with each other
// but only if they have the same value.
public class TwoNTile extends Tile {
private int value;
// Create a tile with the given value of n; should be a power of 2
// though no error checking is done
public TwoNTile(int n){
value = n;
}
// Returns true if this tile merges with the given tile. "this"
// (calling tile) is assumed to be the stationary tile while moving
// is presumed to be the moving tile. TwoNTiles only merge with
// other TwoNTiles with the same internal value.
public boolean mergesWith(Tile moving){
Tile temp = moving;
if(this.value == temp.value){
return true;
}
else{
return false;
}
}
// Produce a new tile which is the result of merging this tile with
// the other. For TwoNTiles, the new Tile will be another TwoNTile
// and will have the sum of the two merged tiles for its value.
// Throw a runtime exception with a useful error message if this
// tile and other cannot be merged.
public Tile merge(Tile moving){
return null;
}
// Get the score for this tile. The score for TwoNTiles are its face
// value.
public int getScore(){
return -1;
}
// Return a string representation of the tile
public String toString(){
return "";
}
}
瓷砖类:
package Game2048;
// Abstract notion of a game tile.
public abstract class Tile{
// Returns true if this tile merges with the given tile.
public abstract boolean mergesWith(Tile other);
// Produce a new tile which is the result of merging this tile with
// the other. May throw an exception if merging is illegal
public abstract Tile merge(Tile other);
// Get the score for this tile.
public abstract int getScore();
// Return a string representation of the tile
public abstract String toString();
}
最佳答案
首先:你可以这样做:
public boolean mergesWith(Tile moving){
return this.value == temp.value;
}
以获得更优雅的解决方案。
其次:您需要将value
变量添加到Tile
类。
public abstract class Tile{
// ...
// add a value to Tile
protected int value;
// ...
}
您已经扩展了 Tile
并添加了新字段。该字段不是 Tile
的字段,Tile
不包含(看不到)它。
基于以下评论:
当您在Tile
中声明值时,您不需要在TwoNTile
中再次声明它。
您可以制作 Tile 对象,只是不使用构造函数。
Tile t = new TwoNTile(...);
是一个有效的 Tile
对象。这样,您就可以实现您已经尝试使用的逻辑。
看static and dynamic binding在 SO 上的 Java 中,或 google it .
关于java - 值无法解析或不是字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31395558/