0

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.

2
  • 2
    You can pass money as an argument to showMoney. Commented Jan 19, 2020 at 19:42
  • Scope of a variable is the part of the program where the variable is accessible. Here in your example, money is accessible only inside main method. The scope of money is the body of main method. You can't access it elsewhere. Commented Jan 19, 2020 at 19:58

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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();
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.