[英]How do you transfer a variable defined in the main method of one class to another?
[英]How to transfer a variable from main method class to another class?
好的...在我的主类中,我要求用户输入一个输入int值。 现在我需要将这个值带到另一个类来进行编码。 怎么样?
主类代码:
neededValue = keyboard.nextInt();
object.methodName(xxxx, yyyy):
来自不同类中的不同方法的代码:
public void methodName(double xxxx, int yyyy) {
int index;
for (index = 0; index < array.length; index++) {
xxxx = array[index].xxxx;
if (xxxx > **neededValue**) {
//some more code
}
}
}
让我们说用户输入是4,如何将“4”转移到其他类?
您需要传递neededValue
作为参数
neededValue = keyboard.nextInt();
object.methodName(xxxx, yyyy,neededValue):
然后在methodName
函数中
public void methodName(double xxxx, int yyyy, int neededValue) {
int index;
for (index = 0; index < array.length; index++) {
xxxx = array[index].xxxx;
if (xxxx > **neededValue**) {
//some more code
}
}
}
希望它有所帮助。
从主要:
neededValue = keyboard.nextInt();
object.methodName(xxxx, yyyy, neededValue):
来自班级:
public void methodName(double xxxx, int yyyy, int neededValue){
int index;
for (index = 0; index < array.length; index++) {
xxxx = array[index].xxxx;
if (xxxx > **neededValue**) {
//some more code
}
}
}
将参数添加到另一个类方法并从主类传递值。如下所示:
class A{
...
neededValue = keyboard.nextInt();
DifferentClass object = new DifferentClass();
object.methodName(xxxx, yyyy, neededValue):
...
}
class DifferentClass{
public void methodName(double xxxx, int yyyy, int neededValue) {
...
}
}
nextValue
变量直接传递给方法,例如: object.methodName(xxxx, yyyy, nextValue)
或者你可以在对象的类A中声明一个int变量:
int someValue;
并通过构造函数或setter设置它
object = new A(nextValue);
or object.setNextValue(nextValue)
然后,你的invoke object.methodName(xxxx, yyyy)
将使用对象内的'someValue'字段
有多种方法,下面列出的很少,
i)在您的方法中创建参数(在其他解决方案中解释)。
ii)使用类中的get / set方法在类中创建变量(在其他解决方案中进行了解释)。
iii)在你的班级中创建一个静态变量(如下所述)
您可以在班级中拥有静态变量,
private static int neededValue;
在您的主要内容中,您可以为其分配值。
ClassName.neededValue = keyboard.nextInt();
object.methodName(xxxx, yyyy):
你可以直接在你的类方法中使用,
public void methodName(double xxxx, int yyyy){
int index;
for (index = 0; index < array.length; index++) {
xxxx = array[index].xxxx;
if (xxxx > ClassName.neededValue) {
//some more code
}
}
}
免责声明:在使用之前了解有关静态关键字的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.