我编写了以下类(class):
public class Hello {
public static void showMoney(){
System.out.println("Money: " + money);
}
public static void main(String[] args){
int money = 1000;
showMoney();
}
}
我想使用 showMoney()
函数查看我的钱,但 showMoney()
函数无法识别主方法中的钱变量。有什么办法可以正确地做到这一点吗?
谢谢。
很抱歉问了这个愚蠢的问题,因为我是编程新手。
最佳答案
在这种情况下最正确的方法是将数据作为参数传递:
// Have this method accept the data as a parameter
public static void showMoney(int passedMoney){
System.out.println("Money: " + passedMoney);
}
public static void main(String[] args){
int money = 1000;
// Then pass it in here as an argument to the method
showMoney(money);
}
关于java - 如何在另一个函数中定义的函数中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59813728/