public class MethodTest05{ public static void main(String[] args){ } public static int m(){ boolean flag=true; //编译器不负责运行,只负责讲道理 if(flag){ return 1; } } } /* 上面代码会编译报错--错误: 缺少返回语句 上面返回值类型不是void,所以在方法执行结束之后,必须使用-return 值;没有则会编译报错 上面的程序有if,也就是有个判断,只有flag为true的时候,才会执行{}里的return语句, 但是对于编译器来说,知道falg是个布尔类型,对于编译器来说,falg有可能是true,也有可能是false, 那{}里的return语句,就有可能执行,也有可能不执行,这时编译器就无法确定这里的return一定会执行, */ //解决方案 /*加个else,这时就可以保证有个分支语句百分百的会得到执行 */ public class MethodTest05{ public static void main(String[] args){ } public static int m(){ boolean flag=true; if(flag){ return 1; }else{ return 2; } } }
原文:https://www.cnblogs.com/wx1995/p/13286955.html