15-110 Introduction to Programming (Reid-Miller)

HOMEWORK 7 - due Saturday, 12 June 2010
Part I (electronic copy) & Part II due at 11:59PM Saturday, 12 June 2010 on the Handin system.
Part I (identical paper copy) due at the beginning of class Monday, 14 June 2010.

Read Sections 5.1-5.5 in your textbook and answer the following questions based on your readings and the course lectures.

Part I

Download the zip file Homework7.zip that contains a an Eclispe project for Part II of this assignment. Put answers to this part in a single file named PartI in one of following file formats: plain text (PartI.txt), rich text(PartI.rtf) or Word (PartI.doc, not docx). Put this file in th project folder Homework7.

1. A student wrote a method findMin that returns the minimum of an array of data. Here is the code that the student wrote:

public static double findMin() {

    double min = data[0];

    for (int i = 1; i <= data.length(); i++) {
        if (data[i] < data[i-1]) min = data[i];
    }

    return min;
}
Identify and correct FOUR errors made by the student in the code above. Explain each error including whether it is a syntax, runtime, or logical error.

2. In addition to being able to write code from a description of a problem, another skill is to be able to understand other people's code. In a short sentence, for each method below, state what the method does, that is, its purpose? Your answer should NOT explain how it is doing what it does. It should state the outcome. For example, for the first question (assuming it has been corrected) your answer would be something like "the method finds the minimum of the all the elements in an array".

For this problem, it is critical that you do not try to run these methods on the computer, nor even hint to your friends what the answer might be. To gain the most benefit of the exercise, you should reason your way through the code and derive the pattern on your own and without using the computer. If after a long time of hard thinking you cannot figure out what the code is doing, as a hint, you may run the code on various input and see if you can find the pattern.

(a)

public int mystery1(String s1, char c){
    int n = 0;
    
    for (int index = 0; index < s1.length(); index++){
        if (s1.charAt(index) == c) n++;
    }
    return n;
}

(b)

    
public static void mystery2(int[] data) {
    if (data == null || data.length == 0) {
        return;
    }

    double y = 0;
    for (int i = 1; i < data.length; i++) {
        y += data[i];
    }

    y = y / data.length;
    
    for (int i = 1; i < data.length; i++) {
        if (data[i] > y) {
            System.out.println(data[i]);
        }
    }
}

(c)

public boolean mystery3(int[] nums, int n) {

    boolean flag = true;
    int len = nums.length;

    if (if n < 0 || n > len) flag = false;
  
    int i = 0;
    while( i < n && flag) {
        if (nums[i] != nums[len - n + i]) {
            flag = false;
        }
        i++ ;
    }
    return flag;
}

(d)

public static String mystery4(String s1, String s2) {
     
    String ss = "";

    int len1 = s1.length() - 1; 
    int len2 = s2.length() - 1 ;

    int index = 0;

    while ( (index < Math.min(len1, len2) )  
        &&  (s1.charAt(index) == s2.charAt(index)) ) {

        ss = ss + s1.charAt(index);
        index++;
    }
    return ss;
}

3. Some researchers have been taking daily water samples from the Monongahela River just down stream from a cement plant. They want to know which reading was the most alkaline.

(a) Complete the following static method which returns the index of the maximum pH value in an array of pH samples. If more that one index of the array equals the maximum, return the index of the oldest sample (closest to the beginning of the array).

    public static int findMaxIndex(double[] pH) {

        int maxIndex = ______;   // start with max at the first position

        for (int i = 1; i < pH.length; i++) {

                if (pH[i] ____  ________________________) {

                        maxIndex = ___________________;
                }
        }

        if (___________________) return -1;

        else return maxIndex;
    }

(b) Suppose the water sample readings for the month of June are stored in an double array referenced by variable june. Write a Java code fragment that prints the day that was the most alkaline and the alkalinity for that day.

4.
(a) Consider the method swap that is defined as follows:

public static void swap(char x, char y) {
	char temp = x;
	x = y;
	y = temp;
}

What is the output of the following Java code fragment?

char m = 'M';
char r = 'R';
swap(m, r);
System.out.println(m + " " + r);

(b) Consider a second overloaded method swap that is defined as follows:

public static void swap(char[] data) {
	char temp = data[0];
	data[0] = data[1];
	data[1] = temp;
}

What is the output of the following Java code fragment?

char[] charArray = {'M', 'R'};
swap(charArray);	
System.out.println(charArray[0] + " " + charArray[1]);

(c) Explain why the answers to parts (a) and (b) are not the same.

5. The static method areEqual returns true if the two int array parameters have exactly the same values in the same order, and false if the arrays are different. If the array lengths are different then return false. For example, for the arrays

{1, 2, 3} and {1, 2, 3} it will return true
{1, 2} and {1, 2, 3} it it will return false
{2, 3, 3} and {3, 3, 3} it will return false
{3, 2, 1, 0} and {3, 4, 1, 0} it will return false
{} and {} it will return true.

Complete this method:

   public static boolean areEqual( int[] array1, int[] array2)

Part II

BACKGROUND

In the game of Hangman, a player tries to guess a secret word by guessing the letters of the word one at a time. The game starts by displaying a row of dashes (-), one for each letter in the secret word. Each time the player guesses a letter that is in the word, the game reveals all occurrences of that letter in the secret word, along with any previously revealed letters. If the player guesses all the letters of the word before making 7 incorrect guesses, then the player wins. Otherwise, the player loses.

ASSIGNMENT

In the Homework7 project there are two classes you are to complete. The Hangman class selects the secret word and maintains the status of the game. The HangmanGame contains the main method and interacts with the player, ensuring the player's input is valid and updating the game.

The Hangman class

There are the following fields:

The HangmanGame class

This class contains a main method that interacts with the user to solve the puzzle. All the user input and output is done in this class.

Start by creating a Hangman object. Then show the current status of the game and ask the user for the next guess, repeatedly. The user should be able to use either upper or lower case letters. After each guess report whether the guess is good or bad. Stop the game when either the user made 7 bad guesses or guessed all the letters of the secret word. Finally report whether the user won or lose the game.

As an added feature, if the user guesses the same letter more than once, report the error and ask the user for another guess, without penalty.

SAMPLE RUN (user input in bold italics)

WELCOME TO THE GAME OF HANGMAN!

You have 7 guesses remaining: -------
Letters used: 
Guess a letter: e
Bad guess.

You have 6 guesses remaining: -------
Letters used: E 
Guess a letter: a
Good guess!

You have 6 guesses remaining: -----A-
Letters used: A E 
Guess a letter: i
Bad guess.

You have 5 guesses remaining: -----A-
Letters used: A E I 
Guess a letter: o
Good guess!

You have 5 guesses remaining: --O--A-
Letters used: A E I O 
Guess a letter: r
Good guess!

You have 5 guesses remaining: -RO-RA-
Letters used: A E I O R 
Guess a letter: t
Bad guess.

You have 4 guesses remaining: -RO-RA-
Letters used: A E I O R T 
Guess a letter: m
Good guess!

You have 4 guesses remaining: -RO-RAM
Letters used: A E I M O R T 
Guess a letter: d
Bad guess.

You have 3 guesses remaining: -RO-RAM
Letters used: A D E I M O R T 
Guess a letter: t
You have used T already
Guess a letter: P
Good guess!

You have 3 guesses remaining: PRO-RAM
Letters used: A D E I M O P R T 
Guess a letter: G
Good guess!

YOU WIN!

IMPLEMENTATION STRATEGY

Complete and test each step before going on to the next step.

  1. Start by implementing the Hangman constructor and toString method (the first line of output only). In main create a Hangman object and print it.
  2. Next implement getGuessesRemaining and isGoodGuess. In main add a loop to get the user guess, and print if it is good or bad guess. The loop should continue until the user runs out of guesss.
  3. Then implement hasWon and in main change the loop to continue until the user either wins or runs out of guesses. Add the final statement that the user has won. Now you should have a basic game working.
  4. Finally add the feature that shows the user the letters previously guessed. That is, implement the hasSeenBefore method and update toString to show the letters seen. Then in main, add a loop that continues until the user guesses a letter that the user has not guessed previously.

You should be able to write your program without writing statements of the of the form

  
if (x == true)
    return true;
else
    return false;
where x is some boolean expression. Simply return x.

EXTRA CREDIT

Add an text based picture of a hangman, where you add more part to the picture each time the user makes a bad guess in the following order:
  1. head
  2. neck
  3. left arm
  4. right arm
  5. body
  6. left leg
  7. right leg
Thus, your output might look something like the following, (be creative!):

You have 4 guesses remaining: -RO-RA-
 _____
|     |
|     O
|    \"
|
|
|
|_______

Letters used: A E I O R T 
Guess a letter: m
Good guess!

PROGRAMMING STYLE

As usual, be sure to follow the programming conventions and provide documentation as described in Homework 1 assignment, otherwise you will not receive full credit for you assignment.