我是 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/