简体   繁体   中英

How I Can use a variable in a function which is defined in an another function?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM