Author Archives: graceliana@gmail.com

Chapter 6: Searches


Classwork:
Searches

Screen Shot 2014-11-19 at 8.58.59 PM

//********************************************************************
//  Searches.java       Author: Lewis/Loftus/Cocking
//
//  Demonstrates the linear and binary search algorithms.
//********************************************************************

public class Searches
{
   //-----------------------------------------------------------------
   //  Searches the array of integers for the specified element using
   //  a linear search. The index where the element was found is
   //  returned, or -1 if the element is not found.
   //-----------------------------------------------------------------
   public static int linearSearch (int[] numbers, int key)
   {
      for (int index = 0; index < numbers.length; index++)
         if (key == numbers[index])
            return index;
      return -1;
   }

   //-----------------------------------------------------------------
   //  Searches the array of integers for the specified element using
   //  a binary search. The index where the element was found is
   //  returned, or -1 if the element is not found.
   //  NOTE: The array must be sorted!
   //-----------------------------------------------------------------
   public static int binarySearch (int[] numbers, int key)
   {
      int low = 0, high = numbers.length-1, middle = (low + high) / 2;

      while (numbers[middle] != key && low <= high)
      {
         if (key < numbers[middle])
            high = middle - 1;
         else
            low = middle + 1;
         middle = (low + high) / 2;
      }

      if (numbers[middle] == key)
         return middle;
      else
         return -1;
   }
}


Classwork:
Work on this two assignments

  1. Given the following list of numbers, how many elements of the list would be examined by the linear search algorithm to determine if each of the indicated target elements are on the list? Trace the steps on paper.
15   21   4   17   8   27   1   22   43   57  25   7   53   12   16

a. 17
b. 15
c. 16
d. 45

  1. Describe the general concept of a binary search. Tell the story and be creative.

  2. Given the following list of numbers, how many elements of the list would be examined by the binary search algorithm to determine if each of the indicated target elements are on the list? Trace the steps on paper and hand it in.

1   4   7   8   12   15   16   17   21   22   25   27   43   53   57

a. 17
b. 15
c. 57
d. 45

Assignments:
Self-Review 6.9 and 6.10
MC 6.5
T/F 6.7

Chapter 6: Deck Of Cards ADT

December 9th, 2016

Classwork:
Design and implement a class called Card that represents a standard playing card. Each card has a suit and a face value. A Card ADT represents a standard playing card.

Create a class called DeckOfCards that stores 52 objects of the Card class using ArrayList. Include methods to

  • Shuffle the deck. The shuffle method should assume a full deck.
  • Deal a card
  • Report the number of cards left in the deck
  • In addition:

  • Write the method “printForEach” to print all the cards in the deck using the “for-each” loop.
  • Write the method “printIterator” to print all the cards in the deck using the “ListIterator“.
  • Create a driver class with a main method that deals each card from a shuffled deck, printing each card as it is dealt.




  • 🃏

    Chapter 6: Data set, coin and purse classes (non-generic)

    /**
       This class computes the average of a set of data values.
    */
    public class DataSet
    {
       /**
          Constructs an empty data set.
       */
       public DataSet()
       {
          final int DATA_LENGTH = 100;
          data = new double[DATA_LENGTH];
          dataSize = 0;
       }
    
       /**
          Adds a data value to the data set
          @param x a data value
       */
       public void add(double x)
       {
          if (dataSize >= data.length)
          {  
             // make a new array of twice the size
             double[] newData = new double[2 * data.length];
             // copy over all elements from data to newData
             System.arraycopy(data, 0, newData, 0, data.length);
             // abandon the old array and store in data
             // a reference to the new array
             data = newData;
          }
          data[dataSize] = x;
          dataSize++;
       }
    
       /**
          Gets the average of the added data.
          @return the average or 0 if no data has been added
       */
       public double getAverage()
       {
          if (dataSize == 0) return 0;
          double sum = 0;
          for (int i = 0; i < dataSize; i++)
             sum = sum + data[i];
          return sum / dataSize;
       }
    
       private double[] data;
       private int dataSize;
    }
    
    
    import java.util.Random;
    
    /**
       This program tests the DataSet class by adding 10,000 numbers
       to the data set and computing the average.
    */
    public class DataSetTest
    {
       public static void main(String[] args)
       {
          Random generator = new Random();
          DataSet data = new DataSet();
          final int COUNT = 10000;
          System.out.println("Adding " + COUNT + " random numbers.");
          for (int i = 0; i < COUNT; i++)
          {
             double x = generator.nextDouble();
             data.add(x);
          }
          double average = data.getAverage();
          System.out.println("average=" + average);      
       }
    }
    
    /**
       A coin with a monetary value.
    */
    public class Coin
    {
       /**
          Constructs a coin.
          @param aValue the monetary value of the coin.
          @param aName the name of the coin
       */
       public Coin(double aValue, String aName) 
       { 
          value = aValue; 
          name = aName;
       }
    
       /**
          Gets the coin value.
          @return the value
       */
       public double getValue() 
       {
          return value;
       }
    
       /**
          Gets the coin name.
          @return the name
       */
       public String getName() 
       {
          return name;
       }
    
       public boolean equals(Object otherObject)
       {  
          Coin other = (Coin)otherObject;
          return name.equals(other.name) 
             && value == other.value; 
       }
    
       private double value;
       private String name;
    }
    
    
    import java.util.ArrayList;
    
    /**
       A purse holds a collection of coins.
    */
    public class Purse
    {
       /**
          Constructs an empty purse.
       */
       public Purse()
       {
          coins = new ArrayList();
       }
    
       /**
          Add a coin to the purse.
          @param aCoin the coin to add
       */
       public void add(Coin aCoin)
       {
          coins.add(aCoin);
       }
    
       /**
          Get the total value of the coins in the purse.
          @return the sum of all coin values
       */
       public double getTotal()
       {
          double total = 0;
          for (int i = 0; i < coins.size(); i++)
          {
             Coin aCoin = (Coin)coins.get(i);
             total = total + aCoin.getValue();       
          }
          return total;
       }
    
       private ArrayList coins;
    }
    
    
    
    import javax.swing.JOptionPane;
    
    /**
       This class tests the Purse class by prompting the
       user to add coins into a purse and computing the total
       value of the purse.
    */
    public class PurseTest
    {
       public static void main(String[] args)
       {
          double NICKEL_VALUE = 0.05;
          double DIME_VALUE = 0.1;
          double QUARTER_VALUE = 0.25;
    
          Purse myPurse = new Purse();
    
          boolean done = false;
          while (!done)
          {
             String input 
                = JOptionPane.showInputDialog("Enter coin name or Cancel");
             if (input == null) 
                done = true;
             else
             {
                double value = 0;
                if (input.equals("nickel"))
                   value = NICKEL_VALUE;
                else if (input.equals("dime"))
                   value = DIME_VALUE;
                else if (input.equals("quarter"))
                   value = QUARTER_VALUE;
                if (value != 0)
                {
                   Coin c = new Coin(value, input);
                   myPurse.add(c);
                   double totalValue = myPurse.getTotal();
                   System.out.println("The total is " + totalValue);
                }
             }
          }
          System.exit(0);
       }
    }
    
    

    Chapter 6: ArrayLists and Generic Classes NOT good

    January 13th, 2014

    ArrayLists and Generic Classes

    The ArrayList class is a generic class: ArrayList collects objects of type T.

    /**
       A bank account has a balance that can be changed by 
       deposits and withdrawals.
    */
    public class BankAccount
    {  
       /**
          Constructs a bank account with a zero balance
          @param anAccountNumber the account number for this account
       */
       public BankAccount(int anAccountNumber)
       {   
          accountNumber = anAccountNumber;
          balance = 0;
       }
    
       /**
          Constructs a bank account with a given balance
          @param anAccountNumber the account number for this account
          @param initialBalance the initial balance
       */
       public BankAccount(int anAccountNumber, double initialBalance)
       {   
          accountNumber = anAccountNumber;
          balance = initialBalance;
       }
    
       /**
          Gets the account number of this bank account.
          @return the account number
       */
       public int getAccountNumber()
       {   
          return accountNumber;
       }
    
       /**
          Deposits money into the bank account.
          @param amount the amount to deposit
       */
       public void deposit(double amount)
       {  
          double newBalance = balance + amount;
          balance = newBalance;
       }
    
       /**
          Withdraws money from the bank account.
          @param amount the amount to withdraw
       */
       public void withdraw(double amount)
       {   
          double newBalance = balance - amount;
          balance = newBalance;
       }
    
       /**
          Gets the current balance of the bank account.
          @return the current balance
       */
       public double getBalance()
       {   
          return balance;
       }
    
       private int accountNumber;
       private double balance;
    }
    
    

    A driver class:

    import java.util.ArrayList;
    
    /**
       This program tests the ArrayList class.
    */
    public class ArrayListTester
    {
       public static void main(String[] args)
       {
          ArrayList accounts 
                = new ArrayList();
          accounts.add(new BankAccount(1001));
          accounts.add(new BankAccount(1015));
          accounts.add(new BankAccount(1729));
          accounts.add(1, new BankAccount(1008));
          accounts.remove(0);
    
          System.out.println("Size: " + accounts.size());
          System.out.println("Expected: 3");
          BankAccount first = accounts.get(0);
          System.out.println("First account number: " 
                + first.getAccountNumber());
          System.out.println("Expected: 1015");                  
          BankAccount last = accounts.get(accounts.size() - 1);
          System.out.println("Last account number: " 
                + last.getAccountNumber());
          System.out.println("Expected: 1729");                  
       }
    }
    
    

    A different implementation:
    Note: pay attention to the for-each loops

    import java.util.ArrayList;
    
    /**
       This bank contains a collection of bank accounts.
    */
    public class Bank
    {   
       /**
          Constructs a bank with no bank accounts.
       */
       public Bank()
       {
          accounts = new ArrayList();
       }
    
       /**
          Adds an account to this bank.
          @param a the account to add
       */
       public void addAccount(BankAccount a)
       {
          accounts.add(a);
       }
       
       /**
          Gets the sum of the balances of all accounts in this bank.
          @return the sum of the balances
       */
       public double getTotalBalance()
       {
          double total = 0;
          for (BankAccount a : accounts)
          {
             total = total + a.getBalance();
          }
          return total;
       }
    
       /**
          Counts the number of bank accounts whose balance is at
          least a given value.
          @param atLeast the balance required to count an account
          @return the number of accounts having least the given balance
       */
       public int count(double atLeast)
       {
          int matches = 0;
          for (BankAccount a : accounts)
          {
             if (a.getBalance() >= atLeast) matches++; // Found a match
          }
          return matches;
       }
    
       /**
          Finds a bank account with a given number.
          @param accountNumber the number to find
          @return the account with the given number, or null if there
          is no such account
       */
       public BankAccount find(int accountNumber)
       {
          for (BankAccount a : accounts)
          {
             if (a.getAccountNumber() == accountNumber) // Found a match
                return a;
          } 
          return null; // No match in the entire array list
       }
    
       /**
          Gets the bank account with the largest balance.
          @return the account with the largest balance, or null if the
          bank has no accounts
       */
       public BankAccount getMaximum()
       {
          if (accounts.size() == 0) return null;
          BankAccount largestYet = accounts.get(0);
          for (int i = 1; i < accounts.size(); i++) 
          {
             BankAccount a = accounts.get(i);
             if (a.getBalance() > largestYet.getBalance())
                largestYet = a;
          }
          return largestYet;
       }
    
       private ArrayList accounts;
    }
    
    

    A driver class:

    /**
       This program tests the Bank class.
    */
    public class BankTester
    {
       public static void main(String[] args)
       {
          Bank firstBankOfJava = new Bank();
          firstBankOfJava.addAccount(new BankAccount(1001, 20000));
          firstBankOfJava.addAccount(new BankAccount(1015, 10000));
          firstBankOfJava.addAccount(new BankAccount(1729, 15000));
    
          double threshold = 15000;
          int c = firstBankOfJava.count(threshold);
          System.out.println("Count: " + c);
          System.out.println("Expected: 2");
          
          int accountNumber = 1015;
          BankAccount a = firstBankOfJava.find(accountNumber);
          if (a == null) 
             System.out.println("No matching account");
          else
             System.out.println("Balance of matching account: " + a.getBalance());
          System.out.println("Expected: 10000");
                   
          BankAccount max = firstBankOfJava.getMaximum();
          System.out.println("Account with largest balance: " 
                + max.getAccountNumber());
          System.out.println("Expected: 1001");
       }
    }
    

    Classwork:
    Modify the Purse class to be a generic class and to use a for-each loop.

    Homework:
    Implement the following methods in the Purse class:

    
       /**
          Counts the number of coins in the purse
          @return the number of coins
       */
       public int count()
       {
         
       }
    
       /**
          Tests if the purse has a coin that matches
          a given coin.
          @param aCoin the coin to match
          @return true if there is a coin equal to aCoin
       */
       public boolean find(Coin aCoin)
       {
    
       }
    
       /**
          Counts the number of coins in the purse that match
          a given coin.
          @param aCoin the coin to match
          @return the number of coins equal to aCoin
       */
       public int count(Coin aCoin)
       {
    
       }
    
       /**
          Finds the coin with the largest value. 
          (Precondition: The purse is not empty)
          @return a coin with maximum value in this purse
       */
       Coin getMaximum()
       {
    
       }
    
    

    ***********************************************************************************************

    The following code and concepts are for more in-depth knowledge of generics and type parameters.

    A Generic Version of the Box Class

    
    /**
     * Generic version of the Box class.
     * @param  the type of the value being boxed
     */
    public class Box {
        // T stands for "Type"
        private T t;
    
        public void set(T t) { this.t = t; }
        public T get() { return t; }
    }
    
    

    Invoking and Instantiating a Generic Type

    To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer:

    Box integerBox;

    You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument — Integer in this case — to the Box class itself.

    Like any other variable declaration, this code does not actually create a new Box object. It simply declares that integerBox will hold a reference to a “Box of Integer”, which is how Box is read.

    An invocation of a generic type is generally known as a parameterized type.

    To instantiate this class, use the new keyword, as usual, but place between the class name and the parenthesis:

    Box integerBox = new Box();

    The most commonly used type parameter names are:
    E – Element (used extensively by the Java Collections Framework)
    K – Key
    N – Number
    T – Type
    V – Value
    S,U,V etc. – 2nd, 3rd, 4th types

    Chapter 6: Arrays as parameters


    Chapter 6: Arrays and ArrayLists
    Arrays of Objects

    arrays as parameters

    • An entire array can be passed as a parameter to a method. Because an array is an object, when an entire array is passed as a parameter, a copy of the reference to the original array is passed.
    • A method that receives an array as a parameter can permanently change an element of the array because it is referring to the original element value. The method cannot permanently change the reference to the array itself because a copy of the original reference is sent to the method. These rules are consistent with the rules that govern any object type.
    • An element of an array can be passed to a method as well. If the element type is a primitive type, a copy of the value is passed. If that element is a reference to an object, a copy of the object reference is passed. As always, the impact of changes made to a parameter inside the method depends on the type of the parameter.
    //********************************************************************
    //  GradeRange.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the use of an array of String objects.
    //********************************************************************
    
    public class GradeRange
    {
       //-----------------------------------------------------------------
       //  Stores the possible grades and their numeric lowest value,
       //  then prints them out.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          String[] grades = {"A", "A-", "B+", "B", "B-", "C+", "C", "C-",
                             "D+", "D", "D-", "F"};
    
          int[] cutoff = {95, 90, 87, 83, 80, 77, 73, 70, 67, 63, 60, 0};
          
          for (int level = 0; level < cutoff.length; level++)
             System.out.println (grades[level] + "\t" + cutoff[level]);
       }
    }
    
    
    //********************************************************************
    //  NameTag.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the use of command line arguments.
    //********************************************************************
    
    public class NameTag
    {
       //-----------------------------------------------------------------
       //  Prints a simple name tag using a greeting and a name that is
       //  specified by the user.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          System.out.println ();
          System.out.println ("     " + args[0]);
          System.out.println ("My name is " + args[1]);
          System.out.println ();
       }
    }
    
    

    filling arrays of objects

  • We must always take into account an important characteristic of object arrays: The creation of the array and the creation of the objects that we store in the array are two separate steps.
  • When we declare an array of String objects, for example, we create an array that holds String references. The String objects themselves must be created separately.
  • The String objects are created using string literals in an initializer list, or, in the case of command-line arguments, they are created by the Java runtime environment.
  • This issue is demonstrated in the Tunes program and its accompanying classes. Listing 6.7 shows the Tunes class, which contains a main method that creates, modifies, and examines a compact disc (CD) collection. Each CD added to the collection is specified by its title, artist, purchase price, and number of tracks.
  • //********************************************************************
    //  Tunes.java       Author: Lewis/Loftus/Cocking
    //
    //  Driver for demonstrating the use of an array of objects.
    //********************************************************************
    
    public class Tunes
    {
       //-----------------------------------------------------------------
       //  Creates a CDCollection object and adds some CDs to it. Prints
       //  reports on the status of the collection.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          CDCollection music = new CDCollection ();
    
          music.addCD ("By the Way", "Red Hot Chili Peppers", 14.95, 10);
          music.addCD ("Come On Over", "Shania Twain", 14.95, 16);
          music.addCD ("Soundtrack", "The Producers", 17.95, 33);
          music.addCD ("Play", "Jennifer Lopez", 13.90, 11);
    
          System.out.println (music);
    
          music.addCD ("Double Live", "Garth Brooks", 19.99, 26);
          music.addCD ("Greatest Hits", "Stone Temple Pilots", 15.95, 13);
    
          System.out.println (music);
       }
    }
    
    
  • The CDCollection class contains an array of CD objects representing the collection.
  • It maintains a count of the CDs in the collection and their combined value.
  • It also keeps track of the current size of the collection array so that a larger array can be created if too many CDs are added to the collection.
  • The collection array is instantiated in the CDCollection constructor. Every time a CD is added to the collection (using the addCD method), a new CD object is created and a reference to it is stored in the collection array.
  • Each time a CD is added to the collection, we check to see whether we have reached the current capacity of the collection array. If we didn’t perform this check, an exception would eventually be thrown when we try to store a new CD object at an invalid index.
  • If the current capacity has been reached, the private increaseSize method is invoked, which first creates an array that is twice as big as the current collection array.
  • Each CD in the existing collection is then copied into the new array.
  • Finally, the collection reference is set to the larger array. Using this technique, we theoretically never run out of room in our CD collection.
  • The user of the CDCollection object (the main method) never has to worry about running out of space because it’s all handled internally.
  • //********************************************************************
    //  CDCollection.java       Author: Lewis/Loftus/Cocking
    //
    //  Represents a collection of compact discs.
    //********************************************************************
    
    import java.text.NumberFormat;
    
    public class CDCollection
    {
       private CD[] collection;
       private int count;
       private double totalCost;
    
       //-----------------------------------------------------------------
       //  Creates an initially empty collection.
       //-----------------------------------------------------------------
       public CDCollection ()
       {
          collection = new CD[100];
          count = 0;
          totalCost = 0.0;
       }
    
       //-----------------------------------------------------------------
       //  Adds a CD to the collection, increasing the size of the
       //  collection if necessary.
       //-----------------------------------------------------------------
       public void addCD (String title, String artist, double cost,
                          int tracks)
       {
          if (count == collection.length)
             increaseSize();
    
          collection[count] = new CD (title, artist, cost, tracks);
          totalCost += cost;
          count++;
       }
    
       //-----------------------------------------------------------------
       //  Returns a report describing the CD collection.
       //-----------------------------------------------------------------
       public String toString()
       {
          NumberFormat fmt = NumberFormat.getCurrencyInstance();
          String report = "******************************************\n";
          report += "My CD Collection\n\n";
    
          report += "Number of CDs: " + count + "\n";
          report += "Total cost: " + fmt.format(totalCost) + "\n";
          report += "Average cost: " + fmt.format(totalCost/count);
    
          report += "\n\nCD List:\n\n";
    
    
          for (int cd = 0; cd < count; cd++)
             report += collection[cd].toString() + "\n";
    
          return report;
       }
    
       //-----------------------------------------------------------------
       //  Doubles the size of the collection by creating a larger array
       //  and copying the existing collection into it.
       //-----------------------------------------------------------------
       private void increaseSize ()
       {
          CD[] temp = new CD[collection.length * 2];
    
          for (int cd = 0; cd < collection.length; cd++)
             temp[cd] = collection[cd];
    
          collection = temp;
       }
    }
    
    
    
    //********************************************************************
    //  CD.java       Author: Lewis/Loftus/Cocking
    //
    //  Represents a compact disc.
    //********************************************************************
    
    import java.text.NumberFormat;
    
    public class CD
    {
       private String title, artist;
       private double cost;
       private int tracks;
    
       //-----------------------------------------------------------------
       //  Creates a new CD with the specified information.
       //-----------------------------------------------------------------
       public CD (String name, String singer, double price, int numTracks)
       {
          title = name;
          artist = singer;
          cost = price;
          tracks = numTracks;
       }
    
       //-----------------------------------------------------------------
       //  Returns a description of this CD.
       //-----------------------------------------------------------------
       public String toString()
       {
          NumberFormat fmt = NumberFormat.getCurrencyInstance();
    
          String description;
    
          description = fmt.format(cost) + "\t" + tracks + "\t";
          description += title + "\t" + artist;
    
          return description;
       }
    }
    
    

    An Object of a Wrapper Class

    Wrapper objects can be used anywhere that objects are required instead of primitive type values. For example, you can collect a sequence of floating-point numbers in an ArrayList.

    Conversion between primitive types and the corresponding wrapper classes is automatic. This process is called auto-boxing (even though auto-wrapping would have been more consistent).

    For example, if you assign a number to a Double object, the number is automatically “put into a box”, namely a wrapper object.
    Double d = 29.95; // auto-boxing; same as Double d = new Double(29.95);

    Wrapper objects are automatically “unboxed” to primitive types.
    double x = d; // auto-unboxing; same as double x = d.doubleValue();

    ArrayList data = new ArrayList();
    data.add(29.95);
    double x = data.get(0);

    The UML class diagram of the Tunes program.
    Screen Shot 2014-11-16 at 11.25.19 AM

    Recall that the open diamond indicates aggregation (a has-a relationship). The cardinality of the relationship is also noted: a CDCollection object contains zero or more CD objects.

    Classwork:
    Programming Projects 6.9

     
    Homework: Programming Projects 6.6

    Chapter 6: Arrays


    Chapter 6: Arrays and ArrayLists

    Highlights review:

    • In Java, arrays are objects
    • Arrays can be create with the “new” operator: int[] height = new int[11]
    • Arrays can also be created in using this format: int[] scores = {76, 87, 99}
    • The index operator [ ] performs automatic bounds checking
    • Beware of the off-by-one errors in a program
    • Either syntax int[] grades or int grades[] is correct

    NOTE: The following programs and the pdf are stored in edmodo’s folder. Get familiar with all these programs and their algorithms to further develop assignments.

    BasicArray

    //********************************************************************
    //  BasicArray.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates basic array declaration and use.
    //********************************************************************
    
    public class BasicArray
    {
       final static int LIMIT = 15;
       final static int MULTIPLE = 10;
                       
       //-----------------------------------------------------------------
       //  Creates an array, fills it with various integer values,
       //  modifies one value, then prints them out.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          int[] list = new int[LIMIT];
          
          //  Initialize the array values
          for (int index = 0; index < LIMIT; index++)
             list[index] = index * MULTIPLE;
          
          list[5] = 999;  // change one array value
          
          for (int index = 0; index < LIMIT; index++)
             System.out.print (list[index] + "  ");
          
          System.out.println ();
       }
    }
    
    

    [collapse]
    Primes

    //********************************************************************
    //  Primes.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the use of an initializer list for an array.
    //********************************************************************
    
    public class Primes
    {
       //-----------------------------------------------------------------
       //  Stores some prime numbers in an array and prints them.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19};
          
          System.out.println ("Array length: " + primeNums.length);
    
          System.out.println ("The first few prime numbers are:");
    
          for (int scan = 0; scan < primeNums.length; scan++)
             System.out.print (primeNums[scan] + "  ");
    
          System.out.println ();
       }
    }
    
    

    [collapse]

    Printing an array of integers in reverse order:

    ReverseOrder

    //********************************************************************
    //  ReverseOrder.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates array index processing.
    //********************************************************************
    
    import java.util.Scanner;
    
    public class ReverseOrder
    {
       //-----------------------------------------------------------------
       //  Reads a list of numbers from the user, storing them in an
       //  array, then prints them in the opposite order.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          double[] numbers = new double[10];
          Scanner scan = new Scanner(System.in);
    
          System.out.println ("The size of the array: " + numbers.length);
    
          for (int index = 0; index < numbers.length; index++)
          {
             System.out.print ("Enter number " + (index+1) + ": ");
             numbers[index] = scan.nextDouble();
          }
          
          System.out.println ("The numbers in reverse order:");
    
          for (int index = numbers.length-1; index >= 0; index--)
             System.out.print (numbers[index] + "  ");
          
          System.out.println ();
       }
    }
    
    
    

    Output:
    The size of the array: 10
    Enter number 1: 18.36
    Enter number 2: 48.9
    Enter number 3: 53.3
    Enter number 4: 21.9
    Enter number 5: 34.7
    Enter number 6: 12.5
    Enter number 7: 78.4
    Enter number 8: 98.1
    Enter number 9: 99.0
    Enter number 10: 37.9
    The numbers in reverse order:
    37.9 99.0 98.1 78.4 12.5 34.7 21.9 53.3 48.9 18.36

    [collapse]

    Letter counting

    LetterCount

    //********************************************************************
    //  LetterCount.java       Author: Lewis/Loftus/Cocking
    //
    //  Demonstrates the relationship between arrays and strings.
    //********************************************************************
    
    import java.util.Scanner;
    
    public class LetterCount
    {
       //-----------------------------------------------------------------
       //  Reads a sentence from the user and counts the number of
       //  uppercase and lowercase letters contained in it.
       //-----------------------------------------------------------------
       public static void main (String[] args)
       {
          final int NUMCHARS = 26;
          Scanner scan = new Scanner(System.in);
    
          int[] upper = new int[NUMCHARS];
          int[] lower = new int[NUMCHARS];
    
          char current;   // the current character being processed
          int other = 0;  // counter for non-alphabetics
    
          System.out.println ("Enter a sentence:");
          String line = scan.nextLine();
    
          //  Count the number of each letter occurence
          for (int ch = 0; ch < line.length(); ch++)
          {
             current = line.charAt(ch);
             if (current >= 'A' && current <= 'Z')
                upper[current-'A']++;
             else
                if (current >= 'a' && current <= 'z')
                   lower[current-'a']++;
                else
                   other++;
          }
    
          //  Print the results
          System.out.println ();
          for (int letter=0; letter < upper.length; letter++)
          {
             System.out.print ( (char) (letter + 'A') );
             System.out.print (": " + upper[letter]);
             System.out.print ("\t\t" + (char) (letter + 'a') );
             System.out.println (": " + lower[letter]);
          }
    
          System.out.println ();
          System.out.println ("Non-alphabetic characters: " + other);
       }
    }
    
    

    Output:
    Enter a sentence:
    In Casablanca, Humprey Bogart never says "Play it again, Sam."

    
    A: 0		a: 10
    B: 1		b: 1
    C: 1		c: 1
    D: 0		d: 0
    E: 0		e: 3
    F: 0		f: 0
    G: 0		g: 2
    H: 1		h: 0
    I: 1		i: 2
    J: 0		j: 0
    K: 0		k: 0
    L: 0		l: 2
    M: 0		m: 2
    N: 0		n: 4
    O: 0		o: 1
    P: 1		p: 1
    Q: 0		q: 0
    R: 0		r: 3
    S: 1		s: 3
    T: 0		t: 2
    U: 0		u: 1
    V: 0		v: 1
    W: 0		w: 0
    X: 0		x: 0
    Y: 0		y: 3
    Z: 0		z: 0
    
    

    [collapse]

    Non-alphabetic characters: 14

    Array length: 8
    The first few prime numbers are:
    2  3  5  7  11  13  17  19  
    
    

    Helpful notes for testing purposes:
    Instead of entering manually input, you could put the data in a file like input.data. Take a look at an easy way to read data from a file:

    import java.util.Scanner;
    public class ScannerInTerminal
    {
        public static void main(String [] args)
        {
            Scanner sc = new Scanner(System.in);
            String fromTerm = sc.next();
            System.out.println(fromTerm);
        }
    }
    
    

    Then you can run it in Terminal
    mrseliaTerminal%: java ScannerInTerminal < input.txt 3.14159…
    Classwork:

    Programming Projects 6.1, 6.2, 6.4 and 6.5


    Homework:

    Short Answers 6.1, 6.2 and 6.3
    Read pages 298 through 311