2-Dimensional Arrays in Java

Today, we started to cover 2-dimensional arrays in Java. I decided to start with something very easy:

2-D Array Visual
2-D Array Visual

We have an array with 2 rows and 3 columns. Like all things in Java, we start counting our indices at 0.

As such, the value of [0][0] is Vanilla and [1][0] is Ice Cream. Note that the first number in the reference points to the row and the second number in the reference points to the column.

import java.util.*;
public class TwoDArrays {
    public static void main(String[] args){
        String[][] myBigArray = new String [][] {
            {"Vanilla ", "Chocolate ", "Strawberry "},
            {"Ice Cream", "Cookie", "Candy"}
        };
        System.out.println(myBigArray[0][0] + myBigArray[1][0]);
        System.out.println(myBigArray[0][1] + myBigArray[1][0]);
        System.out.println(myBigArray[0][2] + myBigArray[1][0]);
        
        System.out.println(myBigArray[0][0] + myBigArray[1][1]);
        System.out.println(myBigArray[0][1] + myBigArray[1][1]);
        System.out.println(myBigArray[0][2] + myBigArray[1][1]);
        
        System.out.println(myBigArray[0][0] + myBigArray[1][2]);
        System.out.println(myBigArray[0][1] + myBigArray[1][2]);
        System.out.println(myBigArray[0][2] + myBigArray[1][2]);
    }
}

Line 4 is where we created the 2-dimensional array named “myBigArray”.

Lines 5 and 6 are where we populated the array. Note that line 5 is the first row and line 6 is the second row.

Lines 8 through 18 are where we are outputting text that is “fed” by the 2-D array.

Line 8 concatenates [0][0] with [1][0] which is Vanilla and Ice Cream.

Line 9 concatenates [0][1] with [1][0] which is Chocolate and Ice Cream.

Line 10 concatenates [0][2] with [1][0] which is Strawberry and Ice Cream.

Line 12 concatenates [0][0] with [1][1] which is Vanilla and Cookie.

Line 13 concatenates [0][1] with [1][1] which is Chocolate and Cookie.

Line 14 concatenates [0][2] with [1][1] which is Strawberry and Cookie.

Line 16 concatenates [0][0] with [1][2] which is Vanilla and Candy.

Line 17 concatenates [0][1] with [1][2] which is Chocolate and Candy.

Line 18 concatenates [0][2] with [1][2] which is Strawberry and Candy.

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.*;
import java.io.*;

public class arrayKeys {
  public static void main(String args[]){
    Scanner count = new Scanner(System.in);
    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.in);
    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();
    }
  System.out.println(Arrays.toString(myArray));
  }
}

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.

Coding Bat – Arrays Cluster 1

Today, while I was attending meetings, I assigned my students to complete 4 Coding Bat logic exercises.

CODING BAT – COMMONEND

This exercise requires that the program return TRUE if the first integers or last integers of two given arrays are the same, otherwise, FALSE will be returned.

Here is the code that you start with:

public boolean commonEnd(int[] a, int[] b) {

}

We start with two integer arrays named “a” and “b”.

public boolean commonEnd(int[] a, int[] b) {
  int arrayALength = a.length;
  int arrayBLength = b.length;
  int lastA = a[arrayALength - 1];
  int lastB = b[arrayBLength - 1];
  int firstA = a[0];
  int firstB = b[0];
  if(firstA == firstB || lastA == lastB){
    return true;
  }
  return false;
}

The solution above starts by calculating the length of each array (lines 2 and 3). Remember, whenever you are asked to do anything with the “end” or “last” items, you will almost always need to calculate the length.

On lines 4 & 5, we are establishing variables to hold the last index of each array and lines 6 & 7 are holding the first index of each array.

Finally, lines 8 through 10 are a conditional statement comparing the first indices of each array and the last indices of each array. If either of them are equal, a TRUE is returned. However, if neither is TRUE, then FALSE is returned.

CODING BAT – MAKELAST

This exercise requires that the program calculate the length of a given array and create a new array that is double that length populated with zeros with the exception of the last index. The last index is to populated with the last index of the first array.

Here is the code that you start with:

public int[] makeLast(int[] nums) {

}

We start with a single integer variable named “nums”.

public int[] makeLast(int[] nums) {
 int arrayLength = nums.length;
 int arrayFinalLength = arrayLength * 2;
 int arrayLast = nums[arrayLength - 1];
 int[] num = new int[arrayFinalLength];
 num[arrayLength - 1] = arrayLast;
 return num;
}

As always, since we are asked to do some operation with the “last” or “end”, we must calculate the length of the array. This is done on line 2.

On line 3, we created a variable to hold the length of the new array, which is double the length of the original array.

Line 4 is where we capture the last index of the original array.

On line 5, we create a new integer array named “num” which has a size assigned by the variable that was created on line 3.

On line 6, we replace the last index of the new array with the value of the variable created on line 4.

Finally, on line 7, we return the new array.

CODING BAT – MAKEPI

This exercise requires that the program return the first 3 digits of PI in an array.

Here is the code that you start with:

public int[] makePi() {

}

We start with just the basic class declaration and no variables.

public int[] makePi() {
  int pi[] = {3,1,4};
  return pi;
}

The solution above starts by creating a new integer array named “pi” which is assigned the integers of 3, 1, and 4 on line 2.

On line 3, the array is returned.

Many students struggle to make this problem more challenging than it needs to be. Some try to take the Math.PI constant and populate the array one index at a time. However, this is not necessary and is not outlined as a requirement in the problem.

 

Starting with Arrays

Today, we started working with basic arrays in class. Before we got into them, we compared them to stacks. We discussed some of the applicable uses of stacks and how they are ideal for a queue where records must remain in the order they were received.

After the discussion reviewing stacks, I then compared them to a basic array. We discussed that while we can select and manipulate any index within an array, the array is a finite size. We discussed advantages and disadvantages of the two data structures. We then moved into practicing with some code.

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

import java.util.*;

public class arrays1 {
 public static void main(String args[]){
 int myFirstArray[] = {100, 25, 63, 3, 12, 50, 85};
 
 //Print the Array
 for(int i=0; i<myFirstArray.length; i++){
   System.out.print(myFirstArray[i] + " ");
 }
 
 //Alternate Way to Print the Array
 System.out.println("");
 for(int everyElement: myFirstArray){
   System.out.print(everyElement + " ");
 }
 
 //Adding the Items in the Array
 System.out.println("");
 int total = 0;
 for(int i=0; i<myFirstArray.length; i++){
   total += myFirstArray[i];
 }
 System.out.println("Total is " + total);
 
 //Sorting the Items in the Array
 Arrays.sort(myFirstArray);
 for(int everyElement: myFirstArray){
   System.out.print(everyElement + " ");
 }
 
 //Locate the Largest Item in the Array
 System.out.println("");
 int max = myFirstArray[0];
   for (int i=1;i<myFirstArray.length; i++){
     if (myFirstArray[i] > max)max = myFirstArray[i];
   }
 System.out.println("Max is " + max);
 }
}

We started the notes by creating the array (line 10). We also discussed the difference between:

int[] myFirstArray = {100, 25, 63, 3, 12, 50, 85};

and

int myFirstArray[] = {100, 25, 63, 3, 12, 50, 85};

The first method is the preferred method for JAVA. The second method was added to the syntax to accommodate programmers who had worked in C++.

Lines 13 through 15 focus on how to display the contents of the array using the for loop..

On line 13, we have a for loop that will start iterating (counting) at 0 using the variable “i” to do the counting. The loop will continue to run until “i” is no longer less than the length of the array. After the loop is successfully run, “i” is incremented by 1.

On line 14, we have what will be executed in each iteration of the loop. The instruction says to print myFirstArray[i].

Remember, the first time through the loop, i = 0. So, line 14 will print index 0 of myFirstArray, which is the first record in the array. The second time through the loop, i = 1. At this point, it will print index 1 of myFirstArray, which is the second record in the array. This process will continue until the end of the array is reached.

Lines 19 through 21 focus on how to display the contents of the array using the foreach loop.

On line 19, we start with a for loop but the conditions are completely different. We declare an integer variable named “everyElement” and set it to have the value received from myFirstArray.

Line 20 prints the value of the variable “everyElement”.

The foreach loop runs through until each and every record has been touched.

Lines 25 through 29 discuss how to calculate the sum of the array.

On line 25, we declare an integer variable named “total” with an initial value of 0.

On line 26, we create a for loop identical to the one used on line 13. This will allow us to traverse the entire array.

On line 27, we take the variable “total” and add the currently selected index to it.

  • On the first pass, we have 0 + 100 = 100
  • On the second pass, we have 100 + 25 = 125
  • On the third pass, we have 125 + 63 = 188
  • On the fourth pass, we have 188 + 3 = 191
  • On the fifth pass, we have 191 + 12 = 203
  • On the sixth pass, we have 203 + 50 = 253
  • On the seventh and final pass, we have 253 + 85 = 338

This section could have been solved also using a foreach loop as outlined below:

int total = 0;
for(int everyElement: myFirstArray){
    total += everyElement;
}
System.out.println("Total is " + total);

Lines 32 through 35 cover how to sort an array.

Line 32 uses the sort function of the Arrays sub-library of the java.util library to sort the array. The sort function was imported on line 6.

Line 33 is a foreach loop (identical to the one seen on line 19.

Line 34 prints the array as it did on line 20.

This section could have been solved also using a traditional for loop as outlined below:

Arrays.sort(myFirstArray);
for(int i=0; i<myFirstArray.length; i++){
  System.out.print(myFirstArray[i] + " ");
}

Finally, in lines 39 to 43, we analyze how to locate the largest item in the array.

We start by declaring an integer variable named “max” and assign it the value of index 0 of the array. Since the array was just sorted on line 32, index 0 is now 3. As such, the variable “max” now has a value of 3.

Line 40 uses a slightly modified for loop as it starts iterating at 1 and not 0 as we did on line 13 and on line 26.

Line 41 uses a conditional if statement to check if the current iterated index of the array is greater than the variable “max”. If the statement is TRUE, the variable “max” is assigned the value of the iterated index. If is it FALSE, the variable “max” remains with its currently assigned value. This process repeats until the entire array is traversed.

As has been the case through all of this, you could use a foreach loop on this section of the problem as well. Here is what that code would look like with a foreach loop:

int max = myFirstArray[0];
  for (int everyElement: myFirstArray){
   if (everyElement > max)max = everyElement;
  }
System.out.println("Max is " + max);

Here is the code using traditional for loops:

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

import java.util.*;

public class arrays1 {
 public static void main(String args[]){
 int myFirstArray[] = {100, 25, 63, 3, 12, 50, 85};
 
 //Print the Array with for Loop
 for(int i=0; i<myFirstArray.length; i++){
   System.out.print(myFirstArray[i] + " ");
 }
 
 //Print the Array with foreach Loop
 System.out.println("");
 for(int everyElement: myFirstArray){
   System.out.print(everyElement + " ");
 }
 
 //Adding the Items in the Array
 System.out.println("");
 int total = 0;
 for(int i=0; i<myFirstArray.length; i++){
   total += myFirstArray[i];
 }
 System.out.println("Total is " + total);
 
 //Sorting the Items in the Array
 Arrays.sort(myFirstArray);
 for(int i=0; i<myFirstArray.length; i++){
   System.out.print(myFirstArray[i] + " ");
 }
 
 //Locate the Largest Item in the Array
 System.out.println("");
 int max = myFirstArray[0];
   for (int i=1;i<myFirstArray.length; i++){
     if (myFirstArray[i] > max)max = myFirstArray[i];
   }
 System.out.println("Max is " + max);
 }
}

Here is the code use foreach loops:

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

import java.util.*;

public class arrays1 {
 public static void main(String args[]){
 int myFirstArray[] = {100, 25, 63, 3, 12, 50, 85};
 
 //Print the Array with for Loop
 for(int i=0; i<myFirstArray.length; i++){
   System.out.print(myFirstArray[i] + " ");
 }
 
 //Print the Array with foreach Loop
 System.out.println("");
 for(int everyElement: myFirstArray){
   System.out.print(everyElement + " ");
 }
 
 //Adding the Items in the Array
 System.out.println("");
 int total = 0;
 for(int everyElement: myFirstArray){
   total += everyElement;
 }
 System.out.println("Total is " + total);
 
 //Sorting the Items in the Array
 Arrays.sort(myFirstArray);
 for(int everyElement: myFirstArray){
   System.out.print(everyElement + " ");
 }
 
 //Locate the Largest Item in the Array
 System.out.println("");
 int max = myFirstArray[0];
   for (int everyElement: myFirstArray){
    if (everyElement > max)max = everyElement;
   }
 System.out.println("Max is " + max);
 }
}

As you can see, both result in the same number of lines of code. It would ultimately be programmer’s preference and customer request for which loop structure would be used.