下面是带注释的行,我遇到了无法到达的错误:
public class HotelRoom{
private int rNo;
private int dRented;
private String rType;
private String occName;
**type of accomodation is checked below**
if(rType=="king"){ this.rType=rType; }
else if(rType=="queen"){ this.rType=rType;}
else if(rType=="suite"){ this.rType=rType;}
else{this.rType = "queen"; } }
**accessor**
public int getRoomNumber(){ return rNo; }
public int getDaysRented(){ return dRented; }
**mutator**
public String getRoomType(){ return rType; }
public String getOccupantName(){return occName; }
**setting the value of occupant based on the conditions**
public boolean setOccupant(String guestName, int days){
if(this.occName!=null){ return false; }
this.occName=guestName; this.dRented = days; return true; }
高级方法
public void advanceDay(){
this.dRented = this.dRented - 1;
if(this.dRented <= 0){ this.occName = null; this.dRented = 0;}}
toString方法:
public String toString(){String out = "";
if(occName!=null){out = "Rented"; return out;}
else{ out ="Free"; return out;}
错误行-“无法访问的错误”:
返回“ HotelRoom” + rNo +“:” + rType +“-” + out; }
public static void main (String[] args){
HotelRoom r1 = new HotelRoom(007,"king");
System.out.println(r1);
}
}
答案 0 :(得分:0)
方法toString
(出于可读性原因,我在此报告为重新格式化):
public String toString() {
String out = "";
if (occName != null) {
out = "Rented";
return out; // Exit here
} else {
out ="Free";
return out; // or exit here
}
// Never reachable
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
最后一行永远无法访问,因为您从前一个if
块返回并且在else
块中又也返回,因此没有机会到达最后一行。
我想你喜欢以下行为:
public String toString() {
String out = "";
if (occName != null) {
// Just set out variable
out = "Rented";
} else {
// Just set out variable
out ="Free";
}
// Return a complete string using the previous out variable
return "HotelRoom" + rNo +":" + rType + "-" + out;
}
提示:请始终对您的代码进行格式化,以使其更易于阅读。易于阅读的代码也是易于学习以发现错误的代码。