java - 在Java中访问方法的变量

标签 java variables methods comparison access-modifiers

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

}

最佳答案

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

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

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

以下是全局变量的示例。

public static void main(String[] args){

int c = 30;

公共(public) double 方法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; 
}

}

希望它对你有用。

关于java - 在Java中访问方法的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287997/

相关文章:

java - Cassandra 集群连接中的多个端点

java - 备份mysql数据库java代码

python - 如何为检查按钮分配值并使用它们来计算分数?

javascript - 使用javascript刷新html页面时如何清除按钮点击?

methods - 具有相同名称和数量但类型不同的 Golang 方法

java - Android 应用程序如何使用 >=256Mb 的 RAM?

用于连接到 Sql Server 并从 Eclipse 运行示例查询的 Java 程序

variables - 动态分配的表变量?

java - 编写一个返回字符串偶数索引的方法

python - 在Python中如何区分这个类中什么是方法,什么是对象构造函数?