0

So i'm in a dilemma right now and can't figure out how this works. Say I have an array that I have declared globally in a class like so:

int[] x = new int[size];

I also have a global variable that called size

int size;

However it's value is not declared here. I wish to know how I can pass a value to this global variable via user input or via method calling. I there another way I can declare an array globally and somehow set its size through user input?


Thank you for the input guys. However, it seems like i still have some confusion about this. I was playing around with java swing and wrote the following code:

btnAdd.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            String text = input.getText();
            int b = Integer.parseInt(text); 
            array= new int[size];
            array[c]=b;
            c++;
                        }});

the first bit of code is essentially a button listener, which takes text from a jtextfield, converts it to an int and adds it to the array. I initialized the array globally in the class, but instantiated in the button. I've got 'c' initialzed in the class as a global variable set to 0. Size is also taken from a global variable set to some number.

    JButton btnPrint = new JButton("print");
    btnPrint.addActionListener(
            new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for(int q=0;q<size;q++){
                System.out.println(array[q]);
            }
        }
    });

This buttons gotta print the array out when i click it. But i'm getting a really weird output. For example, I enter these values into an array of size 3: '2' , '5', '100'. I'll then get an output of 0, 0, 100. It's like only printing out the last value of the array. Need help with this please

1
  • A static (global) variable is initialized when the class is loaded, at runtime. If size is initialized with a user-defined value before the class holding x is loaded, it is possible in your described way. Commented Dec 2, 2015 at 12:09

2 Answers 2

2

Declare the array without initializing it :

int[] x;

Once you assign a value to size, instantiate the array :

size = ...
x = new int[size];
Sign up to request clarification or add additional context in comments.

Comments

1

you can do something likewise,

int[] ary; // array declaration....
Scanner scan = new Scanner(System.in); // getting input from console..
int size = scan.nextInt(); // getting input from console and store into size
if(size >= 0){ // check whether user has input proper value or not
   ary = new int[size]; 
}else{
  System.out.println("Invalid Value Entered");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.