如果车辆可用,则返回信息

时间:2014-01-09 07:04:55

标签: java

我希望getStatus方法返回一条消息,说明车辆是空的,如果它处于空或已到达目的地..但我得到一个错误不兼容的类型我不知道我的if语句有什么问题..我对编程很安静,所以如果我的代码完全错误,我很抱歉

 /**
     * Return the status of this Vehicle.
     * @return The status.
     */
    public String getStatus()
    {
            return id + " at " + location + " headed for " +
           destination;
           if (destination = null) {
               System.out.println("This Vehicle is free");
            }
            else if (location=destination) {
                System.out.println ("This Vehicle is free");
            }

    }

4 个答案:

答案 0 :(得分:1)

return id + " at " + location + " headed for " +
           destination;   // code after this statement is unreachable...
  1. 您将无法访问代码错误...您的返回应该是要执行的最后一个语句。
  2. if(destination = null)错误。应该是if(destination == null)。 '='指定值。 '=='比较。

答案 1 :(得分:1)

您的代码给出了编译时错误无法访问的语句。 目的地和位置应该是相同的类型。

public String getStatus() {

if (destination == null) {
System.out.println("This Vehicle is free");
}
else if (location == destination) {
System.out.println ("This Vehicle is free");
}
return id + " at " + location + " headed for " + destination;
}

答案 2 :(得分:0)

if(destination = null)

将始终返回true,因为=用于分配

使用==进行比较

if (destination == null) 

答案 3 :(得分:0)

退货后,其下方的任何内容都不会被执行。你需要在最后做回报。 location=destination destination = null 是错的,因为=是赋值,你想要的是==这是相等的比较。

public String getStatus()
{
    if (destination == null) {
        System.out.println("This Vehicle is free");
    }
    else if (location == destination) {
        System.out.println("This Vehicle is free");
    }

    return (id + " at " + location + " headed for " + destination);
}
相关问题