Category Archives: Class work

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.

First Days: Shannon Entropy – Cryptography

Classwork/Assignment:

NOTE: The following assignment doesn’t require to be Object Oriented.
Generating cryptograms. A cryptogram is obtained by scrambling English text by replacing each letter with another letter. Write a program, Crypto1_YI.java to generate a random permutation of the 26 letters and use this to map letters.
NOTE: It is not necessary to be OOD
Give example: Don’t scramble punctuation or whitespace.

// DS
// ABCDEFGHIJKLMNOPQRSTUVWXYZ
// SDTVBJGXWACIYROLUQPENKMHZF

// SM
/**
[m, n, u, h, y, c, b, s, f, a, i, k, x, r, l, z, w, t, q, o, d, e, p, g, v, j]
please give an all lowercase string to scramble (any non lowercase characters will be skipped
happy make your bed day
smzzv xmiy vldt nyh hmv
*/

Entropy.
The Shannon entropy measures the information content of an input string and plays a cornerstone role in information theory and data compression.

Shannon is famous for having founded information theory.
It was proposed by Claude Shannon in 1948, borrowing upon the concept in statistical thermodynamics. Assuming each character i appears with probability p_{i}, the entropy is defined to be H = – sum p_{i} log_{2}p_{i}, where the contribution is 0 if p_{i} = 0.

Compute entropy of DNA sequence

(a) Write a program, Entropy1_YI.java to read in a ASCII text string from standard input, count the number of times each ASCII character occurs, and compute the entropy, assuming each character appears with the given probabilities.

(b) Repeat part (a) but use Unicode.(Optional)

https://www.khanacademy.org/computing/computer-science/informationtheory/moderninfotheory/v/compressioncodes

GUI: ButtonViewer

November 4th, 2013

import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
   This program demonstrates how to install an action listener.
*/
public class ButtonViewer
{  
   private static final int FRAME_WIDTH = 100;
   private static final int FRAME_HEIGHT = 60;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();
      JButton button = new JButton("Click me!");
      frame.add(button);
     
      ActionListener listener = new ClickListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
   An action listener that prints a message.
*/
public class ClickListener implements ActionListener
{
   public void actionPerformed(ActionEvent event)
   {
      System.out.println("I was clicked.");
   }            
}

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      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;
   }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
   This program demonstrates how an action listener can access 
   a variable from a surrounding block.
*/
public class InvestmentViewer1
{  
   private static final int FRAME_WIDTH = 120;
   private static final int FRAME_HEIGHT = 60;

   private static final double INTEREST_RATE = 10;
   private static final double INITIAL_BALANCE = 1000;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();

      // The button to trigger the calculation
      JButton button = new JButton("Add Interest");
      frame.add(button);

      // The application adds interest to this bank account
      final BankAccount account = new BankAccount(INITIAL_BALANCE);
      
      class AddInterestListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            // The listener method accesses the account variable
            // from the surrounding block
            double interest = account.getBalance() * INTEREST_RATE / 100;
            account.deposit(interest);
            System.out.println("balance: " + account.getBalance());
         }            
      }
     
      ActionListener listener = new AddInterestListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
   This program displays the growth of an investment. 
*/
public class InvestmentViewer2
{  
   private static final int FRAME_WIDTH = 400;
   private static final int FRAME_HEIGHT = 100;

   private static final double INTEREST_RATE = 10;
   private static final double INITIAL_BALANCE = 1000;

   public static void main(String[] args)
   {  
      JFrame frame = new JFrame();

      // The button to trigger the calculation
      JButton button = new JButton("Add Interest");

      // The application adds interest to this bank account
      final BankAccount account = new BankAccount(INITIAL_BALANCE);

      // The label for displaying the results
      final JLabel label = new JLabel("balance: " + account.getBalance());

      // The panel that holds the user interface components
      JPanel panel = new JPanel();
      panel.add(button);
      panel.add(label);      
      frame.add(panel);
  
      class AddInterestListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            double interest = account.getBalance() * INTEREST_RATE / 100;
            account.deposit(interest);
            label.setText("balance: " + account.getBalance());
         }            
      }

      ActionListener listener = new AddInterestListener();
      button.addActionListener(listener);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

/**
   This component displays a rectangle that can be moved. 
*/
public class RectangleComponent extends JComponent
{  
   private static final int BOX_X = 100;
   private static final int BOX_Y = 100;
   private static final int BOX_WIDTH = 20;
   private static final int BOX_HEIGHT = 30;

   private Rectangle box;

   public RectangleComponent()
   {  
      // The rectangle that the paintComponent method draws
      box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(box);
   }

   /**
      Moves the rectangle to the given location.
      @param x the x-position of the new location
      @param y the y-position of the new location
   */
   public void moveTo(int x, int y)
   {
      box.setLocation(x, y);
      repaint();      
   }
} 

import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;

/**
   This program displays a RectangleComponent.
*/
public class RectangleComponentViewer
{  
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;

   public static void main(String[] args)
   {        
      final RectangleComponent component = new RectangleComponent();

      // Add mouse press listener         

      class MousePressListener implements MouseListener
      {  
         public void mousePressed(MouseEvent event)
         {  
            int x = event.getX();
            int y = event.getY();
            component.moveTo(x, y);
         }

         // Do-nothing methods
         public void mouseReleased(MouseEvent event) {}
         public void mouseClicked(MouseEvent event) {}
         public void mouseEntered(MouseEvent event) {}
         public void mouseExited(MouseEvent event) {}
      }
         
      MouseListener listener = new MousePressListener();
      component.addMouseListener(listener);

      JFrame frame = new JFrame();
      frame.add(component);

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
} 

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;

/**
   This component displays a rectangle that can be moved. 
*/
public class RectangleComponent extends JComponent
{  
   private static final int BOX_X = 100;
   private static final int BOX_Y = 100;
   private static final int BOX_WIDTH = 20;
   private static final int BOX_HEIGHT = 30;

   private Rectangle box;

   public RectangleComponent()
   {  
      // The rectangle that the paintComponent method draws 
      box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT);         
   }

   public void paintComponent(Graphics g)
   {  
      Graphics2D g2 = (Graphics2D) g;

      g2.draw(box);
   }

   /**
      Moves the rectangle by a given amount. 
      @param x the amount to move in the x-direction 
      @param y the amount to move in the y-direction 
   */
   public void moveBy(int dx, int dy)
   {
      box.translate(dx, dy);
      repaint();      
   }
}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

/** 	 	 	 	 	 	
   This program moves the rectangle.
*/
public class RectangleMover
{
   private static final int FRAME_WIDTH = 300;
   private static final int FRAME_HEIGHT = 400;

   public static void main(String[] args)
   {
      JFrame frame = new JFrame();

      frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
      frame.setTitle("An animated rectangle");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      final RectangleComponent component = new RectangleComponent();
      frame.add(component);

      frame.setVisible(true);
      
      class TimerListener implements ActionListener
      {
         public void actionPerformed(ActionEvent event)
         {
            component.moveBy(1, 1);
         }
      }

      ActionListener listener = new TimerListener();

      final int DELAY = 100; // Milliseconds between timer ticks
      Timer t = new Timer(DELAY, listener);
      t.start();      
   }
}

Homework: Exercise 4: Enhance the ButtonViewer program so that it prints a message “I was clicked n times!” whenever the button is clicked. The value n should be incremented with each click.

GUI: RectangleComponent

November 5th, 2013

Classwork:
Exercise 5: Write a program,CurrentTime.java that uses a timer to print the current time once a second. Hint: The following code prints the current time:


Date now = new Date(); System.out.println(now);

The Date class is in the java.util package.

Exercise 6: Change the RectangleComponent, BouncingSqr.java for the animation program so that the rectangle bounces off the edges of the component rather than simply moving outside.

Homework:
Exercise 7: Write a program, AnimatedCar.java that animates a car so that it moves across a frame.