Java || Snippet – How To Input Numbers Into An Integer Array & Display Its Contents Back To User
This snippet demonstrates how to place numbers into an integer array. It also shows how to display the contents of the array back to the user via stdout.
REQUIRED KNOWLEDGE FOR THIS SNIPPET
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.Scanner; public class ArrayInput { // global variable declaration static Scanner cin = new Scanner(System.in); final static int ARRAY_SIZE = 100; // const int allocating space for the array public static void main(String[] args) { // declare & initialize variables int numElems = 0; int[] myArray = new int[ARRAY_SIZE]; // declare array which has the ability to hold 100 elements System.out.println("Welcome to My Programming Notes' Java Program.n"); // ask user how many items they want to place in array System.out.print("How many items do you want to place into the array?: "); numElems = cin.nextInt(); System.out.println(""); // user enters data into array using a for loop // you can also use a while loop, but for loops are more common // when dealing with arrays for(int index=0; index < numElems; ++index) { System.out.print("Enter item #"+(index+1)+": "); myArray[index] = cin.nextInt(); } // display data to user System.out.print("nThe current items inside the array are: "); // display contents inside array using a for loop for(int index=0; index < numElems; ++index) { System.out.print("nItem #"+(index+1)+": "+myArray[index]); } System.out.println(""); }// end of main }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output
Welcome to My Programming Notes' Java Program.
How many items do you want to place into the array?: 5
Enter item #1: 12
Enter item #2: 43
Enter item #3: 5
Enter item #4: 643
Enter item #5: 2321The current items inside the array are:
Item #1: 12
Item #2: 43
Item #3: 5
Item #4: 643
Item #5: 2321
Leave a Reply