首页 > 解决方案 > 为什么我在 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);
        }
        }

标签: java

解决方案


该方法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;
}

提示:始终格式化您的代码,使其更易于阅读。易于阅读的代码也是易于学习发现错误的代码。


推荐阅读