简体   繁体   English

主Java中的全局变量

[英]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) : 您可以在main方法内部初始化数组(尽管它不能是final ):

 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? 你想通过nmarket吗? You don't need to pass it, use: market.length 您不需要通过它,请使用: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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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