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

Time:11-16

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?

CodePudding user response:

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

CodePudding user response:

You can continue writing your program like so:

int[] userdata = null;
userdata = new int[10];
System.out.println(userdata);
System.out.println(userdata.length);

The output of this code is similar to:

[I@3d3fcdb0
10
  • Related