Zack
Zack

Reputation: 111

How can you re-initialize an array that was predefined with the value null in Java?

So I am supposed to complete the below program that determines the size of an array based on the int input of the user.

    public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       int userInput = -1;
       int[] userData = null;

But the program starts by declaring the array as : int[] userData = null;

It also starts by declaring the user input variable as -1: int userInput = -1;

The problem of the program is based on re-initializing this array using the int variable scanned from the user as the length of the given array: userInput = scan.nextInt(); So I tried to re-initizile the array using the new input: int[] userData = new int[userInput]; But unsurprisingly Java complains since the array was initialized before (and I'm not supposed to change that).

The question is, is there actually a way to build on the given code or do I have to delete their initial declarations and start over?

Upvotes: 1

Views: 77

Answers (2)

queeg
queeg

Reputation: 9384

You can continue writing your program like so:

int[] userdata = null;
userInput = … ;
userdata = new int[userInput];  // Create new array, and assign to the existing variable. 

Verify.

System.out.println(userdata);
System.out.println(userdata.length);

The output of this code is similar to:

[I@3d3fcdb0
10

Upvotes: 1

Nowhere Man
Nowhere Man

Reputation: 19545

It may be better to declare and initialize the variables as soon as you need them with appropriate values without having to reassign them:

Scanner scan = new Scanner(System.in);
int userInput = scan.nextInt(); // no need to set to -1
int[] userData = new int[userInput]; // no need to set to null

Upvotes: 1

Related Questions