该方法必须返回int类型

Moo*_*Moo 4 java return function

public int computeStyle(String season) {
    if(season.equals("summer")){
        if (this.style.equals("toque")){
            return 8;
        }
        if (this.style.equals("sun visor")){
            return 1;
        }
        if (this.style.equals("fedora")){
            return 6;
        }
    }
    else if(season.equals("winter")){
        if (this.style.equals("toque")){
            return 1;
        }
        if (this.style.equals("sun visor")){
            return 8;
        }
        if (this.style.equals("fedora")){
            return 7;
        }
    }
    else return 5;
}
Run Code Online (Sandbox Code Playgroud)

为什么我一直得到方法必须返回int类型的错误.这个功能有什么问题?它应该在每个可能的场景中返回一个int吗?

Lui*_*oza 6

有两条未涵盖的路径:

public int computeStyle(String season) {
    if(season.equals("summer")){
        if (this.style.equals("toque")){
            return 8;
        }
        if (this.style.equals("sun visor")){
            return 1;
        }
        if (this.style.equals("fedora")){
            return 6;
        }
        //here
    }
    else if(season.equals("winter")){
        if (this.style.equals("toque")){
            return 1;
        }
        if (this.style.equals("sun visor")){
            return 8;
        }
        if (this.style.equals("fedora")){
            return 7;
        }
        //here
    }
    else return 5;
}
Run Code Online (Sandbox Code Playgroud)

解决方案:声明具有defaut返回值的变量并正确分配值:

public int computeStyle(String season) {
    int result = 5;
    if(season.equals("summer")){
        if (this.style.equals("toque")){
            result = 8;
        }
        if (this.style.equals("sun visor")){
            result = 1;
        }
        if (this.style.equals("fedora")){
            result = 6;
        }
    }
    else if(season.equals("winter")){
        if (this.style.equals("toque")){
            result = 1;
        }
        if (this.style.equals("sun visor")){
            result = 8;
        }
        if (this.style.equals("fedora")){
            result = 7;
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)