在 Java 中访问方法的变量

Access a method's variable in Java

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

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

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

}

如果你在 main 的正下方写 "int c = 30;" 那么它就变成了全局变量。

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

如果您在特定方法内编写 "int c = 30;",那么您无法在该特定方法之外访问。

以下是全局变量的例子。

public static void main (String [] args){

int c = 30;

public 双方法 1(){

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

}

希望对你有用。

How can I access the variables of the method "method1" [...] without touching the method1()?

你不能。

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

由于 a 始终为 10,因此您可以改为 if (c > 10)