Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing return statement with switch

public AlertStatus nextStatus(){
    int randNum = randNumGen.nextInt(3);
    switch(randNum){
        case 0: return new AlertStatusGreen();
        case 1: return new AlertStatusYellow();
        case 2: return new AlertStatusRed();
        default: System.out.println("ERROR: no random number.");
    }
}

This is a method in one of the classes for a program I have to make for school. The switch takes a random integer and uses it to return an object of a certain class that is derived from the class AlertStatus.

For some reason I keep getting an error saying "missing return statement }" for line 9 of the above block of code (the very last line in the above code). I don't understand why it's saying this though seeing as I already have return statements for each case.

like image 798
Bernandion Avatar asked Feb 10 '23 19:02

Bernandion


1 Answers

In the default case you aren't returning anything. I think you wanted something like

public AlertStatus nextStatus(){
    int randNum = randNumGen.nextInt(3);
    switch(randNum){
        case 0: return new AlertStatusGreen();
        case 1: return new AlertStatusYellow();
        default: return new AlertStatusRed();
        // default: System.out.println("ERROR: no random number.");
    }
}
like image 171
Elliott Frisch Avatar answered Feb 13 '23 09:02

Elliott Frisch