I have instantiated a String array containing 10 strings. I basically want to ask the user to enter a subject name until all 10 strings are finished, or if the user enters "q" to quit. Once this happens, the String array elements should be printed via the printArray method. This is what I have so far, but I get a "null" value displayed for each value after "The Array Elements:" to make up a total of 10 strings. This happens if I enter "q" after a few entries and not all ten. I'd like to get rid of the "null" values and also if the user doesn't enter "q", after the 10th entry, then it should display the 10 arrays.
{
// Instantiate a String array that can contain 10 items.
String[] array = new String[10];
// Read names of subjects into this array
// and count how many have been read in.
// There may be fewer than 10.
Scanner input = new Scanner(System.in);
System.out.println("Please enter a subject name or enter q to quit: ");
String subject = input.nextLine();
int i=0;
while (!"q".equals(subject))
{
array[i]=subject;
i++;
System.out.println("Please enter a subject name or enter q to quit: ");
subject = input.nextLine();
}
input.close();
System.out.println("The Array Elements:");
// Call printArray to print the names in the array.
printArray(array);
}
/**
* Method printArray prints the String values
* in a partially-filled array, one per line. Only the
* significant items in the array should be printed.
*/
public static void printArray(String[] args)
{
for(String val : args)
System.out.println(val);
}