【问题标题】:Access a method's variable in Java在 Java 中访问方法的变量
【发布时间】:2016-09-14 06:06:33
【问题描述】:

我是 Java 新手,所以我需要帮助。

如何访问方法method1 的变量并将它们与变量int c 进行比较?我应该返回什么?

public static void main (String [] args){

    int c = 30;

 // I want to compare c with a, for example:

    if (c > a)
    {
         System.out.println(c + " is greater than " + a);
    }

}

我想做上面的对比,不碰method1()

public double method1(){

    int a = 10; int b = 20;

    if (a > b)
    { 
        System.out.println(a + " is greater than " + b); 
    } 
    else if (a < b)
    { 
        System.out.println(b + " is greater than " + a); 
    }

   //What should I return?

    return ????; 

}

【问题讨论】:

    标签: java variables methods comparison access-modifiers


    【解决方案1】:

    如果你写的是“int c = 30;”直接在 main 下方,然后它成为全局变量。

    全局变量意味着:“c”可以在方法内部访问(同一个类的任何地方)。

    如果你写的是“int c = 30;”在特定方法内部而不是在该特定方法外部无法访问。

    以下是全局变量的示例。

    public static void main(String [] args){

    int c = 30;
    

    public double method1(){

    int a = 10; 
    
    if (a > c)
    { 
        System.out.println(a + " is greater than " + c); 
        return a;
    } 
    else if (a < c)
    { 
        System.out.println(c + " is greater than " + a);
        return b; 
    }
    

    }

    我希望它对你有用。

    【讨论】:

      【解决方案2】:

      如何在不触及 method1() 的情况下访问方法“method1”[...] 的变量?

      你不能。

      方法中的局部变量只能在该方法内部访问。如果那个方法不能让你看到它们,那么如果不修改方法,你就看不到它们。

      由于 a 始终为 10,您可以改为使用 if (c &gt; 10)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-15
        • 2016-04-18
        • 2016-01-20
        • 2011-07-04
        • 2013-09-08
        • 2023-04-01
        • 2015-08-25
        • 1970-01-01
        相关资源
        最近更新 更多