【问题标题】:The error says "missing return statement" but I do not where to put the return statement错误说“缺少返回语句”,但我不知道将返回语句放在哪里
【发布时间】:2020-04-12 23:11:29
【问题描述】:
public class BakeryBusiness {
    public static void main(String[] args){  
    }
    public void yearsOfBusiness(){
        int myBusinessStarts = 2023;
    }
    public void itemsToSell(){
        String item1 = "birthdayCake";
        String item2 = "pastry";
        String item3 = "coffee";
        String item4 = "bubbleTea";
        System.out.println(item1);
    } 
    public boolean optionsToChoose(){
        boolean sweetIsChose = true;
        if(sweetIsChose = true){
            System.out.println("You have chose a dessert! What will it be?");
        }else{
            System.out.println("Are you craving for salty foods? Choose what you want!");
            return sweetIsChose;
        }
    }
}

我应该在 optionsToChoose 方法的什么地方放置 return 语句?我想打印出“你选择了甜点!会是什么?”

【问题讨论】:

  • optionsToChoose()if 块中缺少返回。
  • int myBusinessStarts = 2023; 也无用,因为变量的范围仅限于此方法。

标签: java methods return


【解决方案1】:

您需要从方法的每个分支返回。在您的情况下,您是从 else 分支返回,但不是从 if 返回。

if (sweetIsChose == true)
    System.out.println("You have chose a dessert! What it it be?");
    return sweeIsChose; //<- you were missing this
}

附注您使用== 进行布尔比较,但您使用了单个=,它用于分配。所以应该是sweetIsChose == true

【讨论】:

  • 永远不要将== 与布尔值一起使用,这既是因为这个拼写错误,也是因为它是不必要的额外内容。
【解决方案2】:

如果sweetIsChosefalse,则只返回一个值。因此,您也必须在 if 语句中指定这一点。

if (sweetIsChose == true)
    System.out.println("You have chose a dessert! What it it be?");
    return sweetIsChose;
} else {
    System.out.println("Are you craving for salty foods? Choose what you want!");
    return sweetIsChose;
}

但是由于你在两个语句中返回相同,你可以让整个事情更清楚一点:

if (sweetIsChose == true)
    System.out.println("You have chose a dessert! What it it be?");
} else {
    System.out.println("Are you craving for salty foods? Choose what you want!");
}
return sweetIsChose;

您的一个小错误是您尝试在 if 语句中为局部变量 sweetIsChose 分配一个新值。所以不要使用sweetIsChose = true,而是使用sweetIsChose == true。但是,您可以省去麻烦,只需将其传递给if (sweetIsChose)

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 2013-03-21
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多