Programming Lab 2 : classes, objects, data types and input/output


CSCI-UA 9102, Data Structures

Exercise 1

  • Exercise 1.1. Complete the class below to design a function which uses input/ouput to return the diameter of a circle, given its radius

public class Circle{
  public static void main(String [] args){

 // 1. start by declaring your variables

// 2. Display the sentence "Value of radius: " on the screen

// 3. Read the input value and store it in the radius variable

// 4. Compute the perimeter using the appropriate formula

/* 5. display the result using the sentence "The circle with radius " 
+ your value of the radius + 
"has as perimeter: "+ the perimeter you just computed */
}

}

  • Exercise 1.2. Given the function below, (1) Write down the main function that displays the result of the function f(x) for x=0, (2) Modify the main function so that it computes the result f(x) for every integer x between -5 and 5, (3) To determine the maximum value of f(x) on [-5,5], compute the value of f(x) for each of those values and store the max in a variable max

public static int f(int x){
  int resultat;
  resultat = -x*x + 3*x - 2;
  return resultat;
}
  • Exercise 1.3. The p-norm of a vector v = (v1,v2,…, vn) is defined as the pth root of the the sum of the components vi raised to the power p. For the special case of p=2, the gives the traditional Euclidean norm which represents the length of the vector. Give an implementation of a method named ‘norm’ such that norm(v, p) returns the p-norm of the vector v where v is represented as an array of coordinates
  • Exercise 1.4.
    • Write an interface Resizable (the interface should have a method resize(double x)) that resizes a shape’s dimension by a factor x.
    • Make a Rectangle class implement Resizable
    • Write a main Method to:
      • Define a Rectangle (width = 2, height = 3)
      • Print the rectangle’s area and perimeter
      • Resize the rectangle by a factor 2
      • Re-print the rectangle’s area and perimeter.
  • Exercise 1.5. Write a Java interface called Lockable that includes the follow- ing methods: setKey, lock, unlock, and locked. The setKey, lock, and unlock methods take an integer parameter that repre- sents the key. The setKey method establishes the key. The lock and unlock methods lock and unlock the object, but only if the key passed in is correct. The locked method returns a boolean that indicates whether or not the object is locked. A Lockable object represents an object whose regular methods are protected: if the object is locked, the methods cannot be invoked; if it is unlocked, they can be invoked. Write a version of the Coin class below so that it is Lockable.

  • 
    //********************************************************************
    //  Coin.java       Author: Lewis/Loftus
    //
    //  Represents a coin with two sides that can be flipped.
    //********************************************************************
    public class Coin
    {
       private final int HEADS = 0;
       private final int TAILS = 1;
       private int face;
       //-----------------------------------------------------------------
       //  Sets up the coin by flipping it initially.
       //-----------------------------------------------------------------
       public Coin()
    {
    flip();
    }
       //-----------------------------------------------------------------
       //  Flips the coin by randomly choosing a face value.
       //-----------------------------------------------------------------
       public void flip()
       {
          face = (int) (Math.random() * 2);
    }
       //-----------------------------------------------------------------
       //  Returns true if the current face of the coin is heads.
       //-----------------------------------------------------------------
       public boolean isHeads()
       {
          return (face == HEADS);
    }
       //-----------------------------------------------------------------
       // Returns the current face of the coin as a string.
       //-----------------------------------------------------------------
       public String toString()
    {
          String faceName;
     if (face == HEADS)
                faceName = "Heads";
    else
                faceName = "Tails";
             return faceName;
          }
    }
    
  • Exercise 1.6. Consider the following specifications for some of the methods from the Graphics class:

    You are given the class Snowman.java given below. Create a revised version of the Snowman applet with the following modifications:
    • Add two red buttons on the upper torso
    • Make the snowman frown instead of smile
    • Move the sun to the upper-right corner of the picture.
    • Display your name in the upper-left corner of the picture.
    • Shift the entire snowman 20 pixels to the right.
    
    
    //********************************************************************
    //  Snowman.java       Author: Lewis/Loftus
    //
    //  Demonstrates basic drawing methods and the use of color.
    //********************************************************************
    
    import javax.swing.*;
    import java.awt.*;
    
    public class Snowman
    {  
       public static void main(String[] args)
       {  
          SnowmanFrame frame = new SnowmanFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setVisible(true);
       }
    }
    
    /**
       A frame that contains a message panel
    */
    class SnowmanFrame extends JFrame
    {
       public SnowmanFrame()
       {
          setTitle("Snowman");
          setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
    
          SnowmanPanel panel = new SnowmanPanel();
          getContentPane().add(panel);
       }
       public static final int DEFAULT_WIDTH = 400;
       public static final int DEFAULT_HEIGHT = 400;  
    }
    
    class SnowmanPanel extends JPanel
    {
       //-----------------------------------------------------------------
       //  Draws a snowman.
       //-----------------------------------------------------------------
       public void paintComponent (Graphics page)
       {
          super.paintComponent(page);
          final int MID = 150;
          final int TOP = 50;
    
          setBackground (Color.cyan);
    
          page.setColor (Color.blue);
          page.fillRect (0, 175, 300, 50);  // ground
    
          page.setColor (Color.yellow);
          page.fillOval (-40, -40, 80, 80);  // sun
    
          page.setColor (Color.white);
          page.fillOval (MID-20, TOP, 40, 40);      // head
          page.fillOval (MID-35, TOP+35, 70, 50);   // upper torso
          page.fillOval (MID-50, TOP+80, 100, 60);  // lower torso
    
          page.setColor (Color.black);
          page.fillOval (MID-10, TOP+10, 5, 5);   // left eye
          page.fillOval (MID+5, TOP+10, 5, 5);    // right eye
    
          page.drawArc (MID-10, TOP+20, 20, 10, 190, 160);   // smile
    
          page.drawLine (MID-25, TOP+60, MID-50, TOP+40);  // left arm
          page.drawLine (MID+25, TOP+60, MID+55, TOP+60);  // right arm
    
          page.drawLine (MID-20, TOP+5, MID+20, TOP+5);  // brim of hat
          page.fillRect (MID-15, TOP-20, 30, 25);        // top of hat
       }
    }
     
    
  • Exercise 1.7. By relying on the Snowman class, write an applet that draws a house with a door (and doorknob), windows, and a chimney. Add some smoke coming out of the chimney and some clouds in the sky
  • Exercise 1.8.
    • Write an abstract class Shape
      • Instance variable: NumSides
      • Constructor that initializes numSides
      • Concrete method: accessor for numSides
      • Abstract methods: getArea(), getPerimeter()
    • Write a concrete subclass Rectangle
      • Instance variables width, height.
    • Write a concrete subclass Triangle
      • Instance variables width, height.
    • In another class, write a main method to define a Rectangle and a Triangle.
  • Exercise 1.9. Design a class named Person and its two subclasses named Student and Employee. Make Faculty and Staff subclasses of Employee. A person has a name, address, phone number, and email address. A student has a class status (freshman, sophomore, junior, or senior). Define the status as a constant. An employee has an office, salary, and date hired. Create an object for the date hired. The MyDate class should satisfy the following specifications: It should contain:
    • Instance variables year, month and day. month is 0-based (i.e. 0 is for January)
    • A no-arg constructor that creates a MyDate object for the current date
    • A constructor that constructs a MyDate object with specified year, month and day
    • A method named setDate(long elapsedTime) that sets a new date for the object using the elapsed time.
    A faculty member has office hours and a rank. A staff member has a title. Override the toString method in each class to display the class name and the person’s name. Draw the UML diagram for the classes and implement them. Write a test program that creates a Person, Student, Employee, Faculty, and Staff, and invokes their toString() methods.
  • Exercise 1.11. We now consider an Account class that should be designed as follows. The class should contain:
    • A private int variable named id for the account (default 0)
    • A private double variable named balance for the account (default 0)
    • A private double variable named annualInterestRate that stores the current interest rate (default 0). We assume all accounts have the same interest rate
    • A private Date variable named dateCreated that stores the date when the account was created.
    • A no-arg constructor that creates a default account
    • A constructor that creates an account with the specified id and initial balance
    • The accessor and mutator methods for id, balance and annualInterestRate
    • The accessor method for dateCreated
    • A method named getMonthlyInterestRate() that returns the monthly interest rate.
    • A method named getMonthlyInterest() that returns the monthly interest
    • A method named withdraw that withdraw a specified amount from the account
    • A method named deposit that deposits a specified amount to the account.
    Note that the method getMonthlyInterest() is to return monthly interest, not the interest rate. Monthly interest is balance * monthlyInterestRate. monthlyInterestRate is annualInterestRate / 12. Note that annualInterestRate is a percentage, e.g., like 4.5%. You need to divide it by 100.
    • Start by writing a test program that creates an Account object with an account ID of 1122, a balance of $20,000, and an annual interest rate of 4.5%. Use the withdraw method to withdraw $2,500, use the deposit method to deposit $3,000, and print the balance, the monthly interest, and the date when this account was created.
    • Then create two subclasses for checking and saving accounts. A checking account has an overdraft limit, but a savings account cannot be overdrawn. Write a test program that creates objects of Account, SavingsAccount, and CheckingAccount and invokes a toString() method that returns a string description of the account.
  • Exercise 1.12. Write a program that consists of three classes A, B and C such that B extends A and C extends B. Each class should define an instance variable named “x” (that is each has its own variable named x). Implement a way for a method in C to access and set A’s version of x to a given value, without changing B or C’s version.
  • Exercise 1.13. Redesign the Progression class to be abstract and generic, producing a sequence of values of generic type T, and supporting a single constructor that accepts an initial value. Make all corresponding modifications to the rest of the classes in our hierarchy so that they remain as nongeneric classes, while inheriting from the new generic Progression class
  • Exercise 1.14. Write an application that reads the length of the sides of a triangle from the user. Compute the area of the triangle using Heron’s formula . Print the area to 3 decimal places.
  • Exercise 1.15. Write an application that prompts for and reads the user first and last name (separately). Then print a string composed of the first letter of the user’s first name followed by the first 5 characters of the user’s last name, followed by a random number in the range 10 to 99. (Similar algorithms are sometimes used to generate usernames for new computer accounts)
  • Exercise 1.16. Write a short Java program that outputs all possible strings formed by using the characters ‘c’, ‘a’, ‘t’, ‘d’, ‘o’ and ‘g’ exactly once.
  • Exercise 1.17. Write a short Java program that takes as input three integers a,b and c and from the Java console, and determines if they can be used in a correct arithmetic formula (in the given order) like “a+b=c”, “a=b-c” or “a*b=c”
  • Exercise 1.18. Write a short Java program that can take a positive integer greater than 2 and write out the number of times one must repeatedly divide this number by 2 before getting a value less than 2.
  • Exercise 1.19. Write a short Java program that takes two arrays a and b of length n storing the int values, and returns the dot product of a and b. That is returns an array c of length n such that c[i] = a[i]*b[i], for i=1,…, n.
Exercise 2

  • Exercise 2.1. Write a short Java program that takes all the lines input to standard input and writes them to standard output in reverse order. That is each line is output in the correct order but the ordering of the lines is reversed.
  • Exercise 2.2. The birthday paradox says that the probability that two people in a room will have the same birthday is more than half, provided that n the number of people in the room is more than 23. This property is not really a paradox but many people find it surprising. Design a Java program that can test this paradox by a series of experiments on randomly generated birthdays, for n=5, 10, 15, 20, …, 100
Exercise 3

  • Exercise 3.1. Design and implement an application that reads an integer value representing a year from the user. The purpose of the program is to determine if the year is a leap year (and therefore has 29 days in February) in the Gregorian calendar. A year is a leap year if it is divisible by 4, unless it is also divisible by 100 but not 400. For example the year 2003 is not a leap year, but 2004 is. The year 1900 is not a leap year because it is divisible by 100, but the year 2000 is a leap year because even though it is divisible by 10, it is also divisible by 400. Produce an error message for any input value less than 1582 (the year the Gregorian calendar was adopted)
  • Exercise 3.2. Modify the solution to the previous exercise so that the user can evaluate multiple years. Allow the user to terminate the program using an appropriate sentinel value. Validate each input value to ensure it is greater than 1582.
  • Exercise 3.3. Design and implement an application that read an integer value and prints the sum of all even integers between 2 and and the input value, inclusive. Print an error message if the input value is less than 2. Prompt accordingly
  • Exercise 3.4. We consider the class below. Create a modified version of this class so that the spaces, punctuation, and changes in upper case and lower case are not considered when determining whether a string is a palindrome. Hint: these issues can be handled in several ways. Think carefully about your design


import java.util.Scanner;
public class PalindromeTester{
  // -----------------------------------------------
  // Test strings to see if they are palindromes 
  // -----------------------------------------------
  public static void main(String [] args){
   String str, another = "y";
   int left; right;
   Scanner scan = new Scanner(System.in);
   while(another.equalsIgnoreCase("y")) // allows y or Y{
    System.out.println("Enter a potential palindrome: ");
    str = scan.nextLine();

    left = 0;
    right = str.length()-1;

    while(str.charAt(left) == str.charAt(right) && left < right){
    left++;
    right--; }
    System.out.println();
    if(left < right) 
        System.out.println("That string is NOT a palindrome");
    else
       System.out.println("That string IS a palindrome");
   System.out.println();
   System.out.print("Test another palindrome (y/n)? ");
   another = scan.nextLine();
}}}