java - 为什么我在 java 代码中出现无法访问的语句错误。需要帮助来解决这个错误
问题描述
下面是注释行,我收到一个无法访问的错误:
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;
}
提示:始终格式化您的代码,使其更易于阅读。易于阅读的代码也是易于学习发现错误的代码。
推荐阅读
- keras - 我在 Keras 上做对了吗?
- facebook-graph-api - Facebook Graph API 调用业务发现 API 时返回错误
- http - 如何创建 405 错误
- javascript - 当另一个复选框以相同的名称被选中时,javascript禁用复选框
- ruby-on-rails - Rails 5与不同外键的关联
- php - React/Php/MySQL - 通过 REST API (AJAX) 以两种方式发送变量
- python - Web DriverException:IEDriverServer.exe 意外退出。状态码是:3
- c# - C# + Selenium:自动化等待
- linux - Linux/Raspberry Pi 命令帮助四舍五入到小数点后 2
- vba - 创建编号列表时 VBA 访问 Word 错误