Coding Bat – sameFirstLast

This exercise requires that the program analyze an array of integers and return TRUE if the array has a length greater than 1 and the first index is the same as the last index.

Here is the code that you start with:

public boolean sameFirstLast(int[] nums) {

}

As you can see, we have a single integer array named nums.

public boolean sameFirstLast(int[] nums) {
 if (nums.length >= 1){
   int first = nums[0];
   int last = nums[nums.length-1];
   if (first == last){
     return true;
   }
   return false;
   }
 return false;
}

We start on line 2 checking to see if the array has a minimum length of 1. If is does not, we skip to line 10 and return FALSE. If the Boolean on line 2 is true, we proceed to line 3.

We then declare an integer variable named “first” to retrieve the value of index 0 (line 3).

We then declare an integer variable named “last” to retrieve the value of the last letter (Line 4)

As was the case when working with strings, to retrieve the last index of the array, we must first calculate its length and then subtract 1 from the total length. This will give us the value of the last index of the array.

Lines 5 through 7 are the conditional Boolean looking to see if the first and last index are the same value. If the Boolean is TRUE, then TRUE is returned.

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.

Coding Bat – delDel

This exercise requires that the program analyze a string to see if it contains the word “del” starting at index position 1. If it does, it is to remove it and display the word with the “del” removed.

Here is the code that you start with:

public String delDel(String str) {

}

As you can see, we have a single string variable named “str”.

public String delDel(String str) {
 if(str.length()>=4 && str.substring(1,4).equals("del")){
 return str.substring(0, 1) + str.substring(4);
 }
 return str;
}

This solution utilizes a conditional if with the Boolean AND to solve the problem.

We start by looking to see if the string is 4 or more characters in length AND if the string starting at index 1 to 4 is “del”.

If this Boolean is TRUE, then we return the string from index 0 to 1 concatenated with the string from index 4 to the end.

If this Boolean is FALSE, then we simply return the string unmodified.

Coding Bat – Cluster 2

Today, while I was working with the FTC 11242 (ERROR 404) robotics team at Ferris Intermediate School for our community outreach efforts, my Computer Science class was assigned to complete 4 different Coding Bat assignments.

CODING BAT – firstTwo

This exercise requires that the program return only the first two characters of a provided string.

Here is the code that you start with:

public String firstTwo(String str) {
 
}

We start with a single string variable named str.

public String firstTwo(String str) {
 if (str.length() < 2){
 return str;
 }
 String firstTwo = str.substring(0,2);
 return firstTwo;
}

The solution above first uses the length method of the String class to determine if the string is less than 2 characters long. If it is, then the entered string is returned as the solution (lines 2 – 4).

Lines 5 – 6 are executed if the string is 2 or more characters in length and uses the substring method of the String class to capture the characters from index 0 to index 2 (first 2 letters of the string) and assigns them to the variable named firstTwo and then returns the value of that variable.

CODING BAT – extraEnd

This exercise requires that the program take the last two letters of the provided string and create a new string that repeats them 3 times.

Here is the code that you start with:

public String extraEnd(String str) {
 
}

We start with a single string variable named str.

public String extraEnd(String str) {
 int strLength = str.length();
 String lastTwo = str.substring(strLength - 2, strLength);
 String extraEnd = lastTwo + lastTwo + lastTwo;
 return extraEnd;
}

Whenever we are doing something involving the end of a string, we must first calculate the length of the string (line 2).

Once we know the length of the string, we can come back 2 characters (line 3).

We then use concatenate to repeat the last 2 characters 3 times (line 4) and output the final solution (line 5).

CODING BAT – conCat

This exercise requires that the program take two entered strings and concatenate the first with the last. However, if the last character of the first string and the first character of the last string are the same, they are NOT to be repeated and one is to be removed.

Here is the code that you start with:

public String conCat(String a, String b) {
 
}

We start with two string variables named “a” and “b”.

public String conCat(String a, String b) {
 int aLength = a.length();
 int bLength = b.length();
 if (aLength == 0 || bLength == 0){
 return a + b;
 }
 String aLastLetter = a.substring(aLength - 1, aLength);
 String bFirstLetter = b.substring(0,1);
 if (aLastLetter.equals(bFirstLetter)){
 return a + b.substring(1, bLength);
 }
 return a + b;
}

The solution above first determines the length of the two strings (lines 2 – – 3). We then look to see if either of the strings is empty (lines 4 – 6) and return the strings as they are.

If both of the strings have text, we then look to see what the last letter of string a is (line 7) and the first letter of string b (line 8). We then compare these two letters to see if they are the same (line 9). If they are, we return string a concatenated with string b with the first letter of string b removed.

If line 9 is false, then we simply return string a concatenated with string b.

CODING BAT – theEnd

This exercise requires that the program display either the first letter of the string (if the Boolean front is true) or the last letter of the string (if the Boolean front is false).

Here is the code that you start with:

public String theEnd(String str, boolean front) {
 
}

As you can see, we have a string variable named str and a Boolean with the value of front.

public String theEnd(String str, boolean front) {
 int strLength = str.length();
 String strFirstLetter = str.substring (0,1);
 String strLastLetter = str.substring (strLength - 1, strLength);
 if (front == true){
 return strFirstLetter;
 }
 return strLastLetter;
}

As always, when we’re asked to do anything with the end of a string, we must first calculate the length of the string (line 2).

We then create variables for the first letter and last letter of the string using the substring method of the String class (lines 3 – 4).

Line 5 looks to see if the Boolean is true. If it is, we return the value of the variable for the first letter of the string (line 6). Otherwise, we return the value of the variable for the last letter of the string (line 8).

Coding Bat – or35

This exercise requires that the program return the value of true if the given number is evenly divisible by either 3 or 5. The instructions encourage us to utilize modulus division to solve this problem.

As a reminder, modulus division is the “remainder” after you solve a division problem.

Here is the code that you start with:

public boolean or35(int n) {
 
}

As you can see, we have a single integer variable named “n”.

public boolean or35(int n) {
  return (n % 3 == 0) || (n % 5 == 0);
}

The provided solution does not utilize variables beyond the single provided n.

public boolean or35(int n) {
 double modFive = n % 5;
 double modThree = n % 3;
 if (modFive == 0 || modThree == 0){
 return true;
 }
 return false;
}

An alternative solution could use variables for the division and inside the conditional statements.

Coding Bat – Cluster 1

Today, while I was working with the FTC 11242 (ERROR 404) robotics team at Ferris Intermediate School for our community outreach efforts, my Computer Science class was assigned to complete 4 different Coding Bat assignments.

Coding Bat – helloName

This exercise requires that the program return an entered name with the word Hello appended to the front and an exclamation point following the name.

Here is the code that you start with:

public String helloName(String name) {
  
}

We start with a string variable named name.

public String helloName(String name) {
  return "Hello " + name + "!";
}

The solution above simply uses the concatenate function to append “Hello ” in front of the name variable and the “!” following it.

Coding Bat – makeAbba

This exercise requires that the program take two input strings of text and place them into the A-B-B-A order.

For example, let’s say that string A is “cat” and string B is “dog”. The output would be catdogdogcat.

Here is the code that you start with:

public String makeAbba(String a, String b) {
  
}

We start with two string variables named a and b.

public String makeAbba(String a, String b) {
  return a + b + b + a;
}

The solution above simply uses the concatenate function to append variable a to variable b to variable b to variable a.

Coding Bat – makeTags

This exercise requires that the program take two entered strings of which the first is an HTML tag and create a formatted HTML instruction with open and closing tags enclosing the second entered string.

Here is the code that you start with:

public String makeTags(String tag, String word) {
  
}

We start with two string variables named tag and word.

public String makeTags(String tag, String word) {
  return "<" + tag + ">" + word + "</" + tag + ">";
}

The solution above simply uses the concatenate function to append the correct text and variables in an HTML syntax structure.

Coding Bat – withoutX

This exercise requires that the program take an entered string that if it start with or ends with “x” the “x” is removed. If there is an “x” in the middle of the letter, it remains.

Here is the code that you start with:

public String withoutX(String str) {
 
}

As you can see, we have a string variable named str.

public String withoutX(String str) {
 int count = str.length();
 if (count == 0){
 return str;
 }
 int secondToLastLetter = count - 1;
 String firstLetter = str.substring(0, 1);
 String lastLetter = str.substring(secondToLastLetter, count);
 if (str.equals("x")){
 str = "";
 }
 else if (firstLetter.equals("x") && (lastLetter.equals("x"))){
 str = str.substring(1,secondToLastLetter);
 }
 else if (firstLetter.equals("x")){
 str = str.substring(1,count);
 }
 else if (lastLetter.equals("x")){
 str = str.substring(0,secondToLastLetter);
 }
 return str;
}

You can see that this problem was little bit more involved because the testing data set included an empty string and a string that was just a single letter x.

Lines 3 – 5 address the situation of a null or empty string.

Lines 6 – 8 create local variables to be used in the other cases presented.

Lines 9 – 11 address the situation of only the letter x.

Lines 12 – 14 address the situation of an x at the front AND an x at the end.

Lines 15 – 17 address the situation of an x only at the front.

Lines 18 – 20 address the situation of an x only at the end.

Line 21 returns what the string will look like with the necessary letter x’s removed.

Coding Bat – in3050

This exercise requires that the program return the value of true if both of two numbers entered are between 30 and 40 (inclusive) or between 40 and 50 inclusive.

Here is the code that you start with:

public boolean in3050(int a, int b) {
  
}

As you can see, we have two integer variables named “a” and “b”.

public boolean in3050(int a, int b) {
  if (a >= 30 && a <= 40 && b >= 30 && b <= 40) {
    return true;
  }
  if (a >= 40 && a <= 50 && b >= 40 && b <= 50) {
    return true;
  }
  return false;
}

In the solution provided, we have a Boolean that returns true if A is any of the following values:

30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40

AND if B is any of the following values:

30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40

We have a second conditional statement that returns true if A is any of the following values:

40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50

AND if B is any of the following values:

40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50

Otherwise, a false is returned.

An alternate solution could also be:

public boolean in3050(int a, int b) {
  if ((a >= 30 && a <= 40 && b >= 30 && b <= 40) || (a >= 40 && a <= 50 && b >= 40 && b <= 50)) {
    return true;
  }
  return false;
}

Here, we have combined the else if portion of the original solution into a BOOLEAN or statement.

Coding Bat – loneTeen

This exercise requires that the program return the value of true if either of two numbers entered is a teen (13 through 19). If both are teens, the program is to return the value of false.

Here is the code that you start with:

public boolean loneTeen(int a, int b) {

}

As you can see, we have two integer variables named “a” and “b”.

public boolean loneTeen(int a, int b) {
 boolean aNotTeen = (a < 13 || a > 19);
 boolean bNotTeen = (b < 13 || b > 19);
 
 return (aNotTeen && !bNotTeen) || (!aNotTeen && bNotTeen); 
}

In the solution, we first created a boolean named “aNotTeen” which returns a value of true if the value of integer “a” is less than 13 OR greater than 19.

We continued by creating a second boolean named “bNotTeen” which returns a value of true if the value of integer “b” is less than 13 OR greater than 19.

Finally, we have the application return the boolean of aNotTeen AND NOT bNotTeen OR the boolean of NOT aNotTeen AND bNotTeen.

Let’s look at what happens if “a” is 12 and “b” is 17:

  • aNotTeen = TRUE
  • bNotTeen = FALSE

So, in the return we have (TRUE && NOT FALSE) || (NOT TRUE && FALSE). As TRUE and NOT FALSE are one and the same and NOT TRUE and FALSE are one and the same, this returns as TRUE.

Let’s look at what happens if “a” is 13 and “b” is 17:

  • aNotTeen = FALSE
  • bNotTeen = FALSE

On the return, we get (FALSE && NOT FALSE) || (NOT FALSE && FALSE). As FALSE and NOT FALSE are opposites, this returns as FALSE.

Coding Bat provides a slightly different solution which is built around whether the integer is a teen.

public boolean loneTeen(int a, int b) {
  boolean aTeen = (a >= 13 && a <= 19);
  boolean bTeen = (b >= 13 && b <= 19);
  
  return (aTeen && !bTeen) || (!aTeen && bTeen);
}

As you can see, their solution is just as elegant as the solution provided above, but just tackles the problem in a different manner.

Using the examples from above of a = 12 and b = 17:

  • aTeen = FALSE
  • bTeen = TRUE

On the return, we get (FALSE && NOT TRUE) OR (NOT FALSE and TRUE).

As both of those are the same, it returns as TRUE. You’ll notice that it works backwards from my return since my boolean is working opposite to their solution.

Coding Bat – icyHot

This exercise requires that the program return the value of true if one of two temperatures entered is less than 0 and the other is greater than 100.

Here is the code that you start with:

public boolean icyHot(int temp1, int temp2) {
 
}

As you can see, we have two integer variables named “temp1” and “temp2”.

public boolean icyHot(int temp1, int temp2) {
 return ((temp1 < 0 && temp2 > 100) || (temp1 > 100 && temp2 < 0));
}

In the solution, we return a boolean for “temp1” is less than 0 AND “temp2” greater than 100 OR “temp1” is greater than 100 AND “temp2” is less than 0.

Let’s look at the following test data:

  • temp1 = -5
  • temp2 = 105

On the return, we have (TRUE && TRUE) OR (FALSE && FALSE). This will return as TRUE.

Let’s now look at another set of test data:

  • temp1 = 5
  • temp2 = 105

On the return, we have (FALSE && TRUE) OR (FALSE && FALSE). This will return as FALSE.

Finally, let’s look the this final set of test data:

  • temp1 = 5
  • temp2 = 95

On the return, we have (FALSE && FALSE) OR (FALSE && FALSE). This will return as FALSE.

Starting with Stacks

Our next unit in Computer Science is working with data structures. So far, all we have done is take keyboard input or hard-coded input and done immediate calculations with it. We’ve not actually stored or manipulated any data.

We’re going to start with stacks as those are arguably the easiest data structure to understand.

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

import java.io.*;
import java.util.*;

public class stacks {
    public static void main(String args[]){
        Stack myStack = new Stack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.push(4);
        myStack.push(5);
        myStack.push(6);
        myStack.push(7);
        myStack.push(8);
        myStack.push(9);
        myStack.push(0);
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
        System.out.println("");
        System.out.println("First Removed Object is: " + myStack.pop());
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
        System.out.println("");
        System.out.println("Next Removed Object is: " + myStack.pop());
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
        System.out.println("");
        System.out.println("Next Removed Object is: " + myStack.pop());
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
        System.out.println("");
        System.out.println("Next Removed Object is: " + myStack.pop());
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
        System.out.println("");
        System.out.println("Next Removed Object is: " + myStack.pop());
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
    }
}

As you can see here, we created a new stack on line 11 named myStack and then pushed the integer 1, 2, 3, 4, 5, 6, 7, 8, 9, & 0 into that stack on lines 12 through 21.

Line 22 displays the content of the stack, which at this moment is the following:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Line 23 uses the search method to display the current position of a searched item, in this case, the integer “1”. Remember, the search method of a stack returns the position relative to the top of the stack. At this point in the application, the integer “1” is located at position 10.

At Line 25, we use the pop method to return the value at the top of the stack. Since this object was handled, it has now been removed from the stack.

Line 26 is identical to line 22 in that it displays the content of the stack at that moment. However, since the top item has been removed from the stack, it now looks like the following:

[1,2,3,4,5,6,7,8,9]

Line 27 is identical to line 23 and provides the position of the searched item, in this case the integer “1” in relation to the top of the stack. Since the top item has been removed, the search item is now one position closer to the top of the stack.

Lines 29-31, 33-35, 37-39, and 41-43 all perform the same functions as lines 25-27. Each time, the top item from the stack is removed, the current stack is displayed, and the position of the searched item in relation to the top of the stack is provided.

Interactive Stacks

Additionally, we will look at adding interactivity to the process as opposed to hard-coding the data.

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

import java.io.*;
import java.util.*;

public class stacks {
    public static void main(String args[]){
        Stack myStack = new Stack();
        Scanner myInput = new Scanner(System.in);
        System.out.print("Enter 10 Integers Separated by a Space and Press Enter: ");
        for(int myCounter=1; myCounter <11; myCounter++){
            myStack.push(myInput.nextInt());
        }
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
        System.out.println("");
        System.out.println("First Removed Object is: " + myStack.pop());
        System.out.println("Current Stack: " + myStack);
        System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
        System.out.println("");
        for(int myPopCounter=1; myPopCounter < 5; myPopCounter++){
            System.out.println("Next Removed Object is: " + myStack.pop());
            System.out.println("Current Stack: " + myStack);
            System.out.println("Value of 1 is located " + myStack.search(1) + " positions from the top of the stack.");
            System.out.println("");
        }
    }
}

Here, you can see that we’ve streamlined the code considerably. What was lines 25 through 43 is now lines 24 through 29! We utilized a for loop to execute the segment of code through 5 iterations.

In addition, the keyboard inputs are being processed through a for loop located at lines 14-16. This loop runs 10 iterations of the nextInt() method of the scanner object myInput and using the push method of the stack object myStack places them into the stack.

This code runs identical to the code above but the user can enter their own data as opposed to having to utilize the hard-coded data.

Items to Discuss

Next class, we’ll be discussing how the search handles multiple occurrences of the same item. For example, let’s say that a user entered their data to create the following stack:

[1,2,3,4,5,1,2,3,4,5]

In this case, if we used the search method to locate the integer “1”, which integer “1” would be displayed?

We will also analyze the advantages and the disadvantages of stacks as a data structure. This will take us to the next data structure, 1-dimensional arrays.