简体   繁体   中英

The error says “missing return statement” but I do not where to put the return statement

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;
        }
    }
}

where in the optionsToChoose method do I put the return statement? I want to print out "You have chose a dessert? What will it be?"

You need to return from each branch of the method. In your case you are returning from else branch but not from if .

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

A side note you do boolean comparison using == but you have used a single = , which is for assignment. So it should be sweetIsChose == true .

Only one value is returned if sweetIsChose is false . So you must specify this in your if statement as well.

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;
}

But since you return the same in both statements, you can make the whole thing a bit clearer:

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;

Also a small mistake of yours is that you try to assign a new value to the local variable sweetIsChose in the if statement. So instead of sweetIsChose = true , use sweetIsChose == true . However, you can save yourself the trouble and just pass it to if (sweetIsChose) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM