zoukankan      html  css  js  c++  java
  • java 方法的返回值

    先直接上一段代码

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

      

  • 相关阅读:
    第二次站立会议6
    第二次冲刺计划会议5
    第二次冲刺计划会议4
    第一次冲刺计划总结
    历史分割
    并查集
    archetype mvn 创建骨架
    protobuf 实战
    grizzly 实战
    RSA 非对称加密
  • 原文地址:https://www.cnblogs.com/homle/p/14038673.html
Copyright © 2011-2022 走看看