[英]How do I call a variable from the public static void main to another class?
我无所不在,一直到处寻找。 我得到了这个代码
public class Main
{
public static void main(String args[])
{
int target = (int) (Math.random() * 1000);
System.out.println("The number is " + target);
}
}
他们要我创建一个使用目标的类Finder,并在for语句中使用它。 我的问题是我不知道如何从此代码中提取目标。 我是一名学生,我们正在使用的书没有帮助。 我尝试用
numberSearch = Main.target
numberSearch = Main.main.target
numberSearch = Main.main()
还有很多其他
您不能在方法外部访问局部变量
您说过“创建一个带有目标的Finder类”,这意味着Finder类应该在构造函数或执行查找的方法上接受目标值作为参数。
// Using constructor
public class Finder {
private int target;
public Finder(int target) {
this.target = target;
}
public void find() {
// perform find of 'this.target' here
}
}
// On find method
public class Finder {
public void find(int target) {
// perform find of 'target' here
}
}
首先,让我们使用选项卡订购代码
public class Main
{
public static void main(String args[])
{
int target = (int) (Math.random() * 1000);
System.out.println("The number is " + target);
}
}
现在,您要做的就是创建一个您要在学校使用的班级的对象(查找器)。 让我们将此对象的标识符设为“ obj”。
public class Main
{
public static void main(String args[])
{
Finder obj = new Finder();
int target = (int) (Math.random() * 1000);
System.out.println("The number is " + target);
}
}
现在,我们已经完成了这一步,您必须在Finder类中创建一个接受整数的方法(因此它可以接受您称为target的变量,因为它本身就是一个int)。 在for循环中使用变量target的此类方法的示例为:
public void forLoopMethod(int target)
{
//Some sort of for loop involving the int target goes here:
for()
{
}
}
然后在名为Main的类中简单地调用forLoopMethod方法
public class Main
{
public static void main(String args[])
{
Finder obj = new Finder();
int target = (int) (Math.random() * 1000);
obj.forLoopMethod(target);
System.out.println("The number is " + target);
}
}
您的问题是您试图在单独的类中查找局部变量。 变量可以在main()之类的方法外部设置,如果它们是公共变量,则可以由另一个类轻松访问。
在main()函数外部,在Main类内部,您将放置numberSearch变量。 然后在Finder中,您可以通过获取Main.numberSearch的值来访问numberSearch。
请注意,如果您的教授希望您使用私有变量,则需要使用getter和setter。
/*How I tested the code*/
public class Main {
public static int numberSearch;
public static void main(String args[]) {
int target = (int) (Math.random() * 1000);
numberSearch = target;
Finder.getResult();
}
}
/*in a separate file*/
public class Finder {
public static void getResult() {
int t = Main.numberSearch;
System.out.println(t);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.