如果public boolean mergesWith(Tile moving)
和true
磁贴具有相同的值,则this
方法将返回moving
。但是当我通过以下操作检查它们是否相同时:
if(this.value == temp.value){
return true;
}
然后它向我显示
temp.value
上的错误,表明值无法解析或不是字段。我该如何解决?
类 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
对象。这样,您可以实现已经尝试使用的逻辑。查看Java on SO上的static and dynamic binding或google it。
关于java - 值无法解析或不是字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31395558/