Java using scanner for user input to set size of array



I want to allow for the user to be able to choose the size of the int array in my program

Right now I have the following code:

public class SortTests {
    private static int size;
    private static int [] myArray = new int [size]; 

    public static void setArraySize() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a whole number to specify the size of the array: ");
        size = scan.nextInt();
        
    }
    
    public static void fillArray() {
        Random randNum = new Random();
        for (int i = 0; i < myArray.length; i++) {
            myArray[i] = randNum.nextInt(100);
        }
    }

I’m not sure why but when I go to test and print my Array.toString it simply prints ”'[]”’ (obviously it is not doing what it should be doing and populating the int array).

Does anyone have any suggestions on how I can tidy my code smell up and make it so this actually works?

Answer

You have created the array already, and your setArraySize changes the size variable only.

public class SortTests {
    private static int size; <-- setArraySize affects this.
    private static int [] myArray = new int [size];  <-- setArraySize does not affect this.  Size was defaulted to 0, so myArray will always be a 0-sized array.

Change to something similar to this:

public class SortTests {
    private static int [] myArray = new int [size]; 

    public static void setArraySize() {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a whole number to specify the size of the array: ");
        int size = scan.nextInt();
        myArray = Arrays.copyOf(myArray, size);
    }


Source: stackoverflow