先直接上一段代码

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		if(flag = true){
			return 1;
		}
	}
}

初一看好像并没有什么问题,在test方法中也有返回值,但是在编译后:

 

 并没有返回值。。。

在test()方法中,编译器只能识别flag是一个boolean类型,但是不能识别字面值,不能识别到底是true还是false,所以编译器认为可能执行,也可能不执行,所有编译器为了确保程序正确性,提示错误。

修改后:

       第一种修改

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		if(flag = true){
			return 1;
		}else{
			return 0;
		}
	}
}

  第二种修改

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		if(flag = true){
			return 1;
		}
		return 0;
	}
}

  第三种修改使用三目运算符

public class MethodTest01{
	public static void main(String[] args){
		
	}
	public static int test(){
		boolean flag = true;
		return flag ? 1:0;
	}
}

  

posted on 2020-11-25 20:58  homle  阅读(1169)  评论(0编辑  收藏  举报