Reputation: 3
I wrote the following class:
public class Hello {
public static void showMoney(){
System.out.println("Money: " + money);
}
public static void main(String[] args){
int money = 1000;
showMoney();
}
}
I Want to see my money with showMoney()
function but showMoney()
function cannot recognize my money variable in the main method. Is there any way to do it properly?
Thank you.
Sorry for dumb question since I'm rookie in Programming.
Upvotes: 0
Views: 36
Reputation: 45750
The most proper way in this scenario is to pass the data in as an argument:
// 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);
}
Upvotes: 1
Reputation: 1710
There are many ways to do so. first and probably the best way is by passing the money argument to the function like this:
public class Hello {
public static void showMoney(int money){
System.out.println("Money: " + money);
}
public static void main(String[] args){
int money = 1000;
showMoney(money);
}
}
another way is by declaring money variable as static field like this:
public class Hello {
private static int money;
public static void showMoney(){
System.out.println("Money: " + money);
}
public static void main(String[] args){
money = 1000;
showMoney();
}
}
Upvotes: 1