Topics Discussed: Arrays, subscripts, iterating through arrays
Source Code Below
15.2
Topics discussed: Same as above
Source Code for Lesson 15-1 / 15-2
import java.util.Scanner; class Jtutorial1 { public static void main(String args[]){ Scanner input = new Scanner(System.in); //int i= 5; i(5); //int anArray[] = new int[5]; //anArray[ | | | | ]; //anArray[0|0|0|0|0]; // initialize to 0 //anArray[0|1|2|3|4]; // index. 0th, 1st, 2nd, 3rd, 4th //anArray[1|2|3|4|5]; // //anArray[ | |3| | ]; // 3 System.out.println("\nHow many items would you like to enter? : "); int x = input.nextInt(); //3 int itemArray[] = new int[x]; double itemCost[] = new double[x]; for (int i = 0; i < itemArray.length; i++){ // initializing arrays to 0 itemArray[i] = 0; // [i] Subscript. itemCost[i] = 0; // anArray[2] i=2 anArray[i] //itemArray / itemCost[ 0 | 0 | 0 ] // 0, 1, 2 } for(int i=0; i< itemArray.length; i++){ System.out.println("\nEnter the unique, item ID: "); itemArray[i] = input.nextInt(); System.out.println("\nEnter the cost for that item: "); itemCost[i] = input.nextDouble(); } System.out.println(); System.out.println(); System.out.println("Price list: "); for(int i=0; i < itemArray.length; i++){ System.out.println("The value of i is: " + i + " Item Number: " + (itemArray[i]) + " = $" + itemCost[i]); } }//end main }//end class //Create an array, to enter user entered numbers. //10 //a, a, a, a, c, c, c, d, f, g
Homework:
ork download copy Create an array of characters that correspond to SOMETHING meaningful to you and output that many characters. Example, my name 'Damien' User enters 3 program outputs 'Dam'
Arrays
Arrays are the most basic multi-variable container made available in java. The syntax is pretty simple, but the implementation can be confusing if you don’t have a programming background. The basic specifications of an array is that it’s a basic, 0-indexed, template’d, data structure that can be created with either explicit values or in an empty state.
int anArray[] = new int[7]; // Creates an array that can hold 7 ints. for(int i=0; i< anArray.length(); i++){ anArray[i] = i; // sets the array equal to it's index based off the iteration in a loop. }
Arrays can be iterated through easily with loops, especially by for loops.
The Subscript
The subscript is the way that we access a certain part of an array. anArray[0]
would refer to the ‘first’ (remember, 0-indexed) location in the array. Therefore the subscript in this case would be 0. Changing the subscript from within a loop is fairly common practice in Object oriented programming.