Abnery Ortiz
Abnery Ortiz

Reputation: 27

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!

Upvotes: 1

Views: 3964

Answers (3)

Abnery Ortiz
Abnery Ortiz

Reputation: 27

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

}

Upvotes: 0

Gavriel
Gavriel

Reputation: 19237

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

Upvotes: -1

Eran
Eran

Reputation: 393831

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

Upvotes: 7

Related Questions