gpt4 book ai didi

java - 我们如何在函数外部使用参数变量而不将其存储到另一个变量中?

转载 作者:行者123 更新时间:2023-12-01 18:43:17 25 4
gpt4 key购买 nike

我们如何在函数外部使用参数变量而不将其存储到另一个变量中?示例:如果我想读取用户输入的值作为参数??

public class CC {

public int f(int a, int b) {
int d, c;
d = a;
c = b;
return a + b;
} // want to use a & b outside

public int q(int a, int b) {
return a + b; // re-initial-is- will delete the previous parameter value;
}

public int w() {
int p = a + b; // error:cannot access or resolve a & b into variables
return p;
}

public int e() {
int u = d + c; // works but this is not the solution
return u;
}

public static void main(String args[]) {
CC obj = new CC();
obj.f(3, 4);
obj.q(8, 9);
obj.w();
obj.e();
}

}

最佳答案

How we can use a parameter variable outside the function without storing it into another variable?

这是不可能的。局部变量的范围仅限于声明它们的方法。所有局部变量都存储在该方法的堆栈帧上。当方法返回时,堆栈帧被破坏,因此所有局部变量和参数都会丢失。

引自JVM Specification - Frames :

A frame is used to store data and partial results, as well as to perform dynamic linking, return values for methods, and dispatch exceptions.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt (it throws an uncaught exception). Frames are allocated from the Java Virtual Machine stack (§2.5.2) of the thread creating the frame. Each frame has its own array of local variables (§2.6.1), its own operand stack (§2.6.2), and a reference to the run-time constant pool (§2.5.5) of the class of the current method.

<小时/>

话虽如此,看起来ab确实应该是你的类的字段。然后,您可以通过将参数传递给构造函数或通过 setter 方法来设置它们。这就是编写面向对象代码的方式。浏览Oracle tutorial on Classes .

例如,参加一个简单的类(class):

class Operation {
private int a;
private int b;

public Operation(int a, int b) {
this.a = a; this.b = b;
}

public int sum() {
return a + b;
}
}

现在,您可以通过传递参数来创建此类的实例,稍后将在 sum() 方法中使用该实例:

Operation operation = new Operation(4, 5);
System.out.println(operation.sum());

您可以沿着这条线修改您的类。请为您的类和变量选择一个更好的名称。还要遵循标准 Java 命名约定。

关于java - 我们如何在函数外部使用参数变量而不将其存储到另一个变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com