4.4k views
5 votes
First, allow the user to enter a numeric value representing how many names they would like to enter. Next, create an array with its size based on that value. Once the array is created, allow the user to enter in names until the array is full. Again, use a for loop to do this

1 Answer

5 votes

Answer:

//Scanner class is imported to allow program receive user input

import java.util.Scanner;

//The Solution class is defined

public class Solution {

// main method that begin program execution is declared

public static void main(String args[]) {

// Scanner object scan is created

Scanner scan = new Scanner(System.in);

// A prompt is displayed to the user

// the prompt asked the user to enter a number

System.out.println("Enter a number: ");

// the user input is assigned to a variable size

int size = scan.nextInt();

// an empty string name is initialized

String name = "";

// A string array called names is initialized

// have the inputed number as size

String names[] = new String[size];

// A for-loop that allow a user to enter name

// and fill the array with it

for(int i = 0; i < size; i++){

// A prompt is displayed asking the user to enter a name

System.out.println("Enter a name: ");

// the received input is assigned to name

name = scan.next();

// name is assigned to an index

names[i] = name;

}

// A blank line is printed for clarity

System.out.println();

// for-loop to loop the array and print the entire element

for(int i = 0; i < size; i++){

System.out.println(names[i]);

}

}

}

Explanation:

The program is well commented and written in Java. A sample image of program output during execution is attached.

First, allow the user to enter a numeric value representing how many names they would-example-1
User Thepunitsingh
by
4.7k points