Arrays with Keyboard Interactivity

Today, we discussed how to create an array with keyboard interactivity. The user will be asked to enter how many numbers they will be entering and then they will be asked to enter numbers separated by a space.

//Program Name: Arrays with Keyboard Input
//Programmer Name: Eric Evans, M.Ed.
//Programmer Organization: Ferris High School
//Program Date: Spring 2017

import java.util.*;
import java.lang.*;

public class arrayKeys {
  public static void main(String args[]){
    Scanner count = new Scanner(;
    System.out.print("How Many Numbers Do You Want to Enter?: ");
    int arraySize = count.nextInt();
    int myArray[] = new int[arraySize];
    Scanner nums = new Scanner(;
    System.out.println("Enter Your " + arraySize + " numbers each separated by a space and press enter when done.");
    for(int counter = 0; counter < arraySize; counter++){
      myArray[counter] = nums.nextInt();

Following the header information (lines 1 through 4) and the imports (lines 6 through 8), we get to the actual application code.

On line 12, we declare a scanner object named “count” which will receive input from the keyboard.

On line 13, we ask the user to enter the number of items they will be entering. Lines 14 assigns the value that is entered as an integer variable named “arraySize”.

Line 15 creates an empty array named “myArray” which is initialized as the size of the “arraySize” variable declared on line 14.

Line 16 declares a second scanner object named “nums” which will receive the integers to the recorded from the keyboard.

On line 17, we ask the user to enter the integers they want recorded separated by a space.

Line 18 opens a for loop. The loop initialization creates an integer variable named “counter” with the value of 0. The loop condition is to run while the variable “counter” is less than the variable “arraySize”, which was declared on line 14. Each pass through the loop increments the value of the variable “counter” by 1.

Each pass through the loop executes line 19, which assigns the next integer in the sequence of numbers from the “nums” scanner to “myArray” in the index (position) declared by the “counter” variable.

Finally, on line 21, we output the contents of “myArray” as a string.

Leave a Reply

Your email address will not be published. Required fields are marked *