Java 为什么可以';我看不到方法外部的方法局部变量吗?
我是Java新手,希望得到一些澄清,我知道我在方法的参数中声明了一个int变量x,但为什么“result”不能解析为变量呢Java 为什么可以';我看不到方法外部的方法局部变量吗?,java,methods,local-variables,Java,Methods,Local Variables,我是Java新手,希望得到一些澄清,我知道我在方法的参数中声明了一个int变量x,但为什么“result”不能解析为变量呢 public class Methods{ public static void main(String[] args) { //f(x) = x * x square(5); System.out.println(result); } //This method static int
public class Methods{
public static void main(String[] args) {
//f(x) = x * x
square(5);
System.out.println(result);
}
//This method
static int square(int x) {
int result = x * x;
}
您可以,但请注意,局部变量仅在其相关函数中定义。因此,即使在
square()
中定义了result
,但在main()
中没有定义它。因此,您要做的是为square
函数返回一个值,并将其存储在main()
内的变量中,如下所示:
public static void main(String[] args) {
int myResult = square(5);
System.out.println(myResult);
}
//This method
static int square(int x) {
int result = x * x; // Note we could just say: return x * x;
return result;
}
既然你是初学者,我就详细解释一下 规则1:局部变量在方法、构造函数或块中声明。
规则2:当输入方法、构造函数或块时,将创建局部变量,一旦退出方法、构造函数或块,该变量将被销毁 规则3:局部变量没有默认值,因此应声明局部变量,并在首次使用前分配初始值
public class Methods{
public static void main(String[] args) {
//f(x) = x * x
square(5);
System.out.println(result); //result! who are you?
//Main will not recognize him because of rule 3.
}
static int square(int x) {
int result = x * x; //you did it as said in rule 1
}//variable result is destroyed because of rule 2.
请仔细阅读代码中的注释
您的代码的解决方案是:
公共类方法{
public static void main(String[] args) {
//f(x) = x * x
int result=square(5);
System.out.println(result); //result! who are you?
//Main will not recognize him because of rule 3.
}
static int square(int x) {
int result1 = x * x; //you did it as said in rule 1
return result1;
}
正如您所说,它是一个局部变量,因此不会在
main()
中定义。您可以返回result
并将其存储在main()中的变量中
而不是.OHHHH!好的。这意味着除了返回值之外,没有其他局部变量可以在main中执行,并且只能使用自己的方法返回?@user3130676是。返回会返回一个值,因此函数调用square(5)
就好像它是数字25
。局部变量只在函数中定义,它们在函数完成后就消失了。但是你可以返回它们的值。返回的值也可以是字符串吗?除了使用System.out.println(square())外,我还有什么其他方法可以返回值在main方法中?@user3130676仅调用函数square()
即可返回值。您可以使用字符串,但您需要知道int square
意味着它期望返回值为整数。如果您希望返回值为字符串,请将其更改为string square
。对,因此它将是正方形(5)(我需要输入一个int,这样它就可以返回一个值)?我不能使用变量“result”,因为它只存在于方法中?在我看来,规则2是错误的。如果输入了某个块,它将不会被创建,如果程序执行达到声明,它将被创建。另一部分是正确的。@Tom具体来说,是的。如果您确认,请随意编辑和更正有些东西,谢谢