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

      

  • 相关阅读:
    C++类中的函数重载
    C++中的友元
    bzoj 2820
    莫比乌斯函数
    bzoj 2440: [中山市选2011]完全平方数
    莫比乌斯反演1
    [转]C++ 指针和引用
    P2756 飞行员配对方案问题
    P2055 [ZJOI2009]假期的宿舍
    P2654 原核生物培养
  • 原文地址:https://www.cnblogs.com/homle/p/14038673.html
Copyright © 2011-2022 走看看