java user-defined array (and user-defined array size) returning [null, null, null, ...]

Ryan Horner picture Ryan Horner · Aug 25, 2015 · Viewed 17.4k times · Source

This is my first question on this site, I'm running this on NetBeans 8.0.2 and trying to print out my user-defined array but it keeps returning null values. For example if you say there are 2 employees and enter both of their names, it will return [null, null]

How to fix this error? I'm a novice.

import java.util.Scanner;
import java.text.DecimalFormat;
import java.util.Arrays;

class Tips_Calculation2 
{
public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);

    System.out.print("How many employees for the week?: ");
    int numberOfEmps = scan.nextInt();

    // counter for the if statement that should return all employees from the array
    int counter = numberOfEmps;

    int[] nOEarray = new int[numberOfEmps];


    System.out.println("\nEnter names of workers up to the entered amount (" + numberOfEmps + "):");


    for(int i = 1; i <= numberOfEmps; i++)
    {
        String nameCycler = scan.next();
        String[] namesArray = new String[i];

        if(counter == i)
        {
            System.out.println(Arrays.toString(namesArray));
        }
    }
}
}

Disregard import java.text.DecimalFormat as I plan to use this import later on in my code. Thank you in advance to anyone who is kind/smart enough to respond.

Answer

wawek picture wawek · Aug 25, 2015

First of all you never put your nameCycler to array. Second of all you create your namesArray every iteration which I think is wrong.