gpt4 book ai didi

java - 如何从 public static void main 调用另一个类的变量?

转载 作者:行者123 更新时间:2023-12-01 22:09:55 24 4
gpt4 key购买 nike

我真的很茫然,到处寻找。我已获得此代码

public class Main
{
public static void main(String args[])
{
int target = (int) (Math.random() * 1000);

System.out.println("The number is " + target);

}

}

他们希望我创建一个类查找器来获取目标并在 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
}
}

关于java - 如何从 public static void main 调用另一个类的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32017143/

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