Java dynamic array sizes?

前端 未结 18 2507
星月不相逢
星月不相逢 2020-11-22 04:37

I have a class - xClass, that I want to load into an array of xClass so I the declaration:

xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
my         


        
18条回答
  •  滥情空心
    2020-11-22 05:34

    I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:

    class MyClass {
        void myFunction () {
            Scanner s = new Scanner (System.in);
            int myArray [];
            int x;
    
            System.out.print ("Enter the size of the array: ");
            x = s.nextInt();
    
            myArray = new int[x];
        }
    }
    

    this assigns your array size to be the one entered at run time into x.

提交回复
热议问题