Shayan Niazi
Shayan Niazi

Reputation: 19

how to take user input that initializes an arrays size (the array is declared globally) JAVA

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

Upvotes: 0

Views: 551

Answers (2)

Vishal Gajera
Vishal Gajera

Reputation: 4207

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

Upvotes: 1

Eran
Eran

Reputation: 393771

Declare the array without initializing it :

int[] x;

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

size = ...
x = new int[size];

Upvotes: 2

Related Questions