【发布时间】:2017-06-30 22:38:24
【问题描述】:
在我的课堂上,我们分配了一个名为 Battleship 的 CodeHS 作业。我被困在第 7 部分的第 2 部分,即 Location 类。练习如下:
下一个要编写的类是 Location.java 文件。 Location 类存储一个网格位置的信息。
一个位置有两个定义属性
1) 这个位置有船吗?
2) 这个位置的状态是什么?
这个状态会是这个位置是未猜到的,我们是命中还是失败。
public static final int UNGUESSED = 0;
public static final int HIT = 1;
public static final int MISSED = 2;
这些是您需要为 Location 类实现的方法。
// Location constructor.
public Location()
// Was this Location a hit?
public boolean checkHit()
// Was this location a miss?
public boolean checkMiss()
// Was this location unguessed?
public boolean isUnguessed()
// Mark this location a hit.
public void markHit()
// Mark this location a miss.
public void markMiss()
// Return whether or not this location has a ship.
public boolean hasShip()
// Set the value of whether this location has a ship.
public void setShip(boolean val)
// Set the status of this Location.
public void setStatus(int status)
// Get the status of this Location.
public int getStatus()
而我的工作如下:
public class Location
{
private int location;
private int hit;
private int miss;
private boolean val;
private int status;
//Implement the Location class here
public static final int UNGUESSED = 0;
public static final int HIT = 1;
public static final int MISSED = 2;
// Location constructor.
public Location(int location){
this.location = location;
}
// Was this Location a hit?
public boolean checkHit(){
if(location == HIT)
return true;
return false;
}
// Was this location a miss?
public boolean checkMiss(){
if(location == MISSED)
return true;
return false;
}
// Was this location unguessed?
public boolean isUnguessed(){
if(location == UNGUESSED)
return true;
return false;
}
// Mark this location a hit.
public void markHit(int hit){
this.hit = hit;
}
// Mark this location a miss.
public void markMiss(int miss){
this.miss = miss;
}
// Return whether or not this location has a ship.
public boolean hasShip(){
return val;
}
// Set the value of whether this location has a ship.
public void setShip(boolean val){
if(status == HIT)
val = true;
else
val = false;
}
// Set the status of this Location.
public void setStatus(int status){
this.status = status;
}
// Get the status of this Location.
public int getStatus(){
if(status == HIT)
return HIT;
else if (status == MISSED)
return MISSED;
else if(status == UNGUESSED)
return UNGUESSED;
}
}
虽然如果我在其他地方出现错误,我真的不会感到惊讶,但我的主要问题是 setShip 布尔方法。我应该如何将其设置为 true(该位置有一艘船)或 false(没有船)。我所拥有的是我最好的猜测,但只有在“射击”之后进行测试时才是正确的。而且我认为该练习希望在此之前对其进行测试。
【问题讨论】:
-
1) 位置应该是
Point(x,y) 吗? 2) 字段val应更改为表示hasShip3) 如果您使用 setter/getter 功能,您会看到您应该设置并获取hasShip值 4) 考虑public boolean checkHit () {return localtion == HIT);}
标签: java methods initialization boolean logic