CS2 10-Jan-2018

Lesson Name:

Stacks vs Arrays

TEKS – §126.34 (Computer Science 2):

  • c.3 – Research and information fluency. The student locates, analyzes, processes, and organizes data. The student is expected to:
  • c.3.D – manipulate data structures using string processing;
  • c.3.F – identify and use the structured data type of one-dimensional arrays to traverse, search, modify, insert, and delete data;

Lesson Objectives:

  1. The student will be able to create and manipulate a stack data structure.
  2. The student will be able to create and manipulate a 1-d array structure.

Materials Needed:

  1. NetBeans
  2. stackedData.dat File (queued phone calls)
  3. arrayData.dat File (numbered list)

Description of Lesson:

Students will create a basic stack of 10 queued phone calls and pull the top item off of the stack. Discussion will focus on the fact that items are read from top to bottom from the data file. As such, items at the bottom of the file are the last ones placed into the stack.

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

public class adam {
    public static void main(String[] args) throws IOException{
    Scanner numbers = new Scanner( new File("stackedData.dat")); //Accesses the data file.
      Stack firstStack = new Stack(); //Constructor to build an empty stack called "firstStack".
      while(numbers.hasNextLine()){ //Opening loop that run as long as the file has a nextLine.
        firstStack.push(numbers.nextLine()); //Loop executes a push to enter the data from the data file to the stack.
      } //Closes the while loop.
      System.out.println("Next Call in Queue is " + firstStack.pop()); //Outputs the item on the top of the stack. Item is removed.
     }
}

Students will then create a 1-D array of a set of numbers. They will manipulate that data set as well.

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

public class billy {
    public static void main(String[] args) throws IOException{
    Scanner nmbrs = new Scanner( new File("arrayData.dat"));
        int[] myNewArray = new int[10];
        int indexNumber = 0;
        while (nmbrs.hasNext()){
            int numberFromFile = nmbrs.nextInt();
            myNewArray[indexNumber] = numberFromFile;
            indexNumber++;
        }
    System.out.println("Unsorted: " + Arrays.toString(myNewArray));
    Arrays.sort(myNewArray);
    System.out.println("Sorted: " + Arrays.toString(myNewArray));
    int subtr = myNewArray[9] - myNewArray[8];
    System.out.println(myNewArray[9] + " - " + myNewArray[8] + " = " + subtr);
    }
}

Grade(s):

  • Daily Grade – Stack (50%) / Array (50%)

Leave a Reply

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