该方法必须返回int类型

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

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

有两条未涵盖的路径:

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

解决方案:使用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; } 

如果返回类型为int,则表示方法必须返回int的方式。

在这种情况下你的外部if else ,你仍然有if块,意味着如果,在外部if else ,如果不满足条件,那么它将不返回任何内容。

在这种情况下,您应该始终在末尾添加一个return语句。

喜欢这个 :

 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; // If everything fails, then it ll return 0 at least return 0; }