[英]why am I getting unreachable statement error in java code. need help to solve this error
下面是注释行,我收到一个无法访问的错误:
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;}
错误行-“无法访问的错误”:
return "HotelRoom" + rNo +":" + rType + "-" + out; }
public static void main (String[] args){
HotelRoom r1 = new HotelRoom(007,"king");
System.out.println(r1);
}
}
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;
}
提示:始终格式化您的代码,使其更具人类可读性。 易于阅读的代码也是易于研究以发现错误的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.