简体   繁体   中英

Global variables in the main Java

I have the following problem, and know why this is giving me some problems. I wonder if there is a way to use somehow nmarked in the declaration of the market array?

public class Main {
         static final int[] market = new int[nmarked];
         public static void main(String[] args) {
         int nmarked=3;
         }
 }

thx a lot!

You can initialize the array inside the main method (it can't be final though) :

 static int[] market;
 public static void main(String[] args) {
     int nmarked=3;
     market = new int[nmarked];
 }

This is a better view of the code:

 public static void main(String[] args) {
     int [] market = new int[3];
     for (int i=0;i<3;i++) market[i]=i;
     Consume_order consume = Consume_order(market);
     consume.start();

 }

 public class Consume_order extends Thread {
   public run(){
      private int[] array;
      public Consume_order(int[] array) {
           this.array=array;
      }
      System.out.println(array[0]);
 }

}

Do you want to pass nmarket? You don't need to pass it, use: market.length

Or:

public class Market {
         final int[] market;
         public Market(int nmarked) {
             market = new int[nmarked];
         }
}

// from main you can call it:

Market market = new Market(3);

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