Category Archives: Homework

Chapter 6: ArrayLists – Purse and Coin

/**
   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) 
         (and) 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 (less than) coins.size(); i++)
      {
         Coin aCoin = (Coin)coins.get(i);
         total = total + aCoin.getValue();       
      }
      return total;
   }

   private ArrayList coins;
}


Chapter 6: ArrayLists and Generic Classes NOPE

January 14th, 2014

ArrayLists and Generic Classes

Classwork:
Write a class Customer with customer number, name, address, and balance.
Write a class Clients. Clients class has an ArrayList to keep all the customers information together. This class has the following methods:
1. add – this method adds a new customer to the ArrayList
2. remove – this method removes the customer from the ArrayList
3. update – this method changes a customer’s balance.
4. getTotal – this method finds the total of all the customers balances.
5. getMaxBal – this method finds the customer with the largest balance and returns the customer object.
6. print – this method prints all the customers information.
7. sortBalance – this method creates a new ArrayList with the customers sorted by balance. This methods prints the customers in sorted order.

Write a driver class to show all the methods above.
NOTE: use generics and for-each loops

Homework: Two questions posted on edmodo.com

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: 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


    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

    Chapter 2: Assignments

    Written Assignments:
    T/F 1-8

    Short Answers

    2.1 What is encapsulation and what is the purpose?
    2.2 What output is produced by the following code fragment? Explain.

    System.out.print (“Test this if you are not sure.”);
    System.out.print (“Another.”);
    System.out.println ();

    2.3 How do you print the following statement with double quotes?
    “To be or not to be, that is the question.”

    2.4 What output is produced by the following statement? Explain.
    System.out.println (“50 plus 25 is “ + 50 + 25);

    2.5 What is the output produced by the following statement? Explain.
    System.out.println (“He thrusts his fists\n\tagainst” +
    “ the post\nand still insists\n\the sees the \”ghost\””);

    2.6 Given the following declarations, what result is stored in each of the listed assignment statements?

    int iResult, num1 = 25, num2 = 40, num3 = 17, num4 = 5;
    double fResult, val1 = 17.0, val2 = 12.78;

    ◗ iResult = num1 / num4;
    ◗ fResult = num1 / num4;
    ◗ fResult = val1 / val2;
    ◗ iResult = num1 / num2;
    ◗ fResult = (double) num1 / num2;
    ◗ fResult = num1 / (double) num2;
    ◗ fResult = (double) (num1 / num2
    ◗ fResult = (int) ((double) num1 / num2); ◗ iResult = num3 % num4;
    ◗ iResult = num 2 % num3; ◗ iResult = num3 % num2;
    ◗ iResult = num2 % num4;

    2.7 For each of the following expressions, indicate the order in which the operators will be evaluated by writing a number beneath each operator.

    ◗ a – b + c – d
    ◗ a / b * c * d
    ◗ a % b / c *d
    ◗ a % b % c % d
    ◗ (a + b) * c+ d * e
    ◗ (a + b) * (c / d) % e

    2.8 What output is produced by the following code fragment?
    String m1, m2, m3;
    m1 = “Quest for the Holy Grail”;
    m2 = m1.toLowerCase();
    m3 = m1 + “ “ + m2;
    System.out.println (m3.replace(‘h’, ‘z’));

    2.9 Write an assignment statement that computes the square root of the sum of num1 and num2 and assigns the result to num3.

    2.10 Write a single statement that computes and prints the absolute value of total.

    2.11 Assuming that a Random object has been created called generator, what is the range of the result of each of the following expressions?

    generator.nextInt(20)
    generator.nextInt(8) + 1

    2.12 Write code to declare and instantiate an object of the Random class (call the object reference variable rand). Then write a list of expressions using the nextInt method that generates random numbers in the following specified ranges, including the endpoints. Use the version of the nextInt method that accepts a single integer parameter.

    ◗ 0 to 10 including both numbers

    ◗ 25 to 50 including both numbers

    ◗ 1 to 10 including both number

    ◗ –10 to 15 including both numbers

    2.13. List all primitive data types you know.

    2.14. What is the difference between a character and a string.

    2.15. Do you need to cast when assigning a double to an integer? why or why not?

    2.16. Do you need to cast when assigning an integer to a double? why or why not?

    Self-review questions at the end of the chapter.

    Coming up next week: Chapter 2 Test
    10 free responses similar to the review questions
    3 String ADT related MC questions – look into the String methods
    1 for-loop MC question
    1 short program similar to this review question:
    Write a main method that prompts the use for two numbers, x and y, and it displays it back the following format: (x,y).

    Chapter 2: Test Review

    Answer these questions:

    Chapter 2 Test Review

    The Java Language
    1. What is encapsulation and what is the purpose?
    2. Explain abstractions. Give an example of an abstraction.
    3. Give the code to concatenate two strings “hello” and “goodbye”.
    4. List the escape sequences and the meaning.
    5. Write the statement to print “Hello World” including the quotes.
    5. List all primitive data types you know.
    6. What is the difference between a character and a string.
    7. Do you need to cast when assigning a double to an integer? why or why not?
    8. Do you need to cast when assigning an integer to a double? why or why not?
    9. Give an example of widening and narrowing type conversion for each.
    10. What is the purpose of casting when using a casting operator in the case of narrowing type conversion.
    11. What does “123456789”.substring(3,6) return?
    12. Write a main method that prompts the use for two numbers, x and y, and it displays it back the following format: (x,y).
    13. Write a code snipped to compare two strings, s1 and s2. If s1 comes first in the lexicographic order, then it will print “move two steps forward” else “move two steps backwards.
    14. What is the result of 21 % 6 when evaluated in a java expression?

    Object Oriented Design
    1. What are classes like?
    2. What is the content of an object variable?
    3. Why the “= =” cannot be used to compare objects?
    4. What is an instance of a class?
    5. In the following code: BankAccount myAcct = new BankAccount(); Is myAcct an object of BankAccount?
    6. What is the purpose of a constructor?
    7. Can you have multiple constructors?
    8. What is the return type of a constructor?
    9. What does the operator new do?
    10. What does it mean a string object is inmutable?
    11. What is a wrapper class? What is autoboxing? Give clear examples.

    Homework:
    Do the self-review questions at the end of the chapter.
    Reflect on this article:
    Screen Shot 2015-09-14 at 8.55.02 PM

    First Days: Cryptography: Number Encryption

    #1. A company wants to transmit data through the wireless network, but they are concerned that their devices may be compromised. All of their data is transmitted as four-digit integers. They have asked you to write a program that will encrypt their data so that it may be transmitted more securely. Your application should read a four-digit integer entered by the user in an input dialog and encrypt it following this sequence of instructions:

    Replace each digit by (the sum of that digit plus 7) modulus 10.
    Swap the first digit with the third.
    Swap the second digit with the fourth.
    Finally, print the encrypted integer.

    Write a java program, NumEncrypt_YI.java to encrypt the 4-digit number entered by the user. Your program must include a beginning message, “Would you like to encrypt another number?” message, and an exit message.

    #2. Write a java program, NumDecrypt_YI.java that prompts the user for an encrypted four-digit integer and decrypts it to form the original number. Just as the previous assignment, your program must include a beginning message, “Would you like to encrypt another number?” message, and an exit message.