Sunday 31 October 2010

Chapter 5 TEST

Part 1:


a&b) I have read the clients specifications and I believe I have a clear understanding of the clients requirements.
I am suppose to create a word guessing game in which a word is randomly chosen and the objective is to figure out the chosen word. The user will be given the length of the word and will have to input words of the same length to discover the word. After inputing a word the user will be told how many letters were correct.  Ex: if the word is PIG and the user puts in POT the output will show 1. In order to quit ot give up the user must type x for every character of the word.Ex: if the word is MAN the user must input XXX.

c) To make this we must have a Responder class which generates a response according to the users input. The responder class represents a response generator object. It is used to generate an automatic response. Since we must read the users input in order to respond, we must also create an InputReader Class. InputReader reads typed text input from the standard text terminal. The text typed by a user is then dividedinto words, and a set of words is provided. We also need a class called WordGuessingGame which implements and puts to use the other classe in order to create the game.

public class WordGuessingGame:

/** This class is implements a Word Guessing Game. The game communicates with the user via input/output messages in the terminal window.
*
* This class uses an object of class InputReader to read input from the user, and an
* object of class Responder to generate responses. It repeatedly
* reads input and generates output until the users wants to leave.


@ version 1.0
@author Jonathan The Beast Schory


public class Responder:



/**
 * The responder class represents a response generator object.
 * It is used to generate an response according to the InputReader class. the response will be generated according to the requirements listed in section a&b.
 * 
 * @author     Jonathan The Beast Schory
 * @version    1.0
 */




public class InputReader:

/**
 * InputReader reads typed text input from the standard text terminal. 
 * the reader will test the input and respond to it according to the requirements listed in section a&b.
 * 
 * @author     Jonathan The Beast Schory
 * @version    1.0
 */




public class InputReader




Part 2:



Discuss (in your blog) the possible uses of each of the following classes in the implementation of the project. You can refer to the class documentation at the Duke site for details of the classes.

a. HashMap

containsKey

public boolean containsKey(java.lang.Object key)

Description copied from interface: Map
Returns true if there is a value associated with key in this map, otherwise returns false.
Specified by:
containsKey in interface Map

Parameters:
key - is the key for which the map is queried as to the existence of an associated value
Returns:
true if there is a (key,value) pair in the map for the specified key, otherwise return false
Perhaps we can use hashmap to determine if the input contains characters from the word the user needs to guess.
*** I am still having trouble clearly understanding the methods and the independent use of hashmaps. Please talk to me next class so we can discuss and you could clarify some of my confusions.***



b. Random

the random class must be used in this project in order to generate a random word which the user must guess. 
For example:
Text File: "There was a young man from Gondwana, who developed a severe case of Pangea, try as he would, he never quite could, find his way back to good old Gondwana."
Word chosen at random (#5) man

c. HashSet

d String
Very important for this project since the whole game is based on guessing a certain word(string) by inputing other words(strings) in the input. We use strings and test them to determine how many characters of the users input are correct. We also use strings for the whole communication with the user. A welcome or Goodbye message are actually strings.



Sunday 24 October 2010

Barnes and Kolling Chapter Five Questions

Barnes and Kolling Chapter Five Questions


1
Open and run the project tech-support-complete.
You run it by creating an object of class SupportSystem and calling its smart() method. Enter some questions you might be having with your software to try out the system. See how it behaves. Type "bye" when you are done.
You do not need to examine the source code at this stage. This project is the complete solution that we will have developed by the end of the chapter. The purpose of this exercise is only to give you an idea of what we plan to acheive.

OK

2
Investigate the String documentation. Then look at the documentation for some other classes.
The Duke University site has documentation for the AP Subset and is very useful for this course because you are not overwhelmed with the full Java library, below.
What is the structure of class documentation?
Which sections are common to all class descriptions?
What is their purpose?

All of them are structured the same a with field,method and constructor.\ summary. these sections breifley describe the purpose of the class
3
Look up the startsWith() method in the documentation for String.
Describe in your own words what it does.

 checks if the beginning of a string at the specified index starts with a certain prefix

4
Is there a method in the String class that tests whether a string ends with a given suffix?
If so, what is it called?
and what are its parameters and return type?

endsWith(String suffix) 
          Tests if this string ends with the specified suffix.

5
Is there a method in the String class that returns the number of characters in the string?
If so, what is it called?
and what are its parameters?

 intlength()
          Returns the length of this string.



6
If you found methods for the two tasks above, how did you find them?
Is it easy or hard to find methods you are looking for?
Why?

the first one was easy since i assumed that if one method is called startwith the other would be names endwith. the other method (length) i am already familiar with.

7
Find the trim() method in the String class's documentation.
Write down the signature of that method.
Write down an example call to that method on a String variable called text.
What does the documentation say about the control characters at the begining of the String?


 Stringtrim()
          Returns a copy of the string, with leading and trailing whitespace omitted.




text.trim()

8

9
Improve the code of the SupportSystem class in the tech-support1 project so that the caseof the input string is ignored.
Use the String class's toLowerCase() method to do this.
Remember that this method will not actually change the string it is called on, but result in the creation of a new one with slightly different contents.
Why is this so?

???? 

10
Find the equals() method in the documentation for class String.
What is the return type of the method?

booleanequals(Object anObject)
          Compares this string to the specified object.
boolean
11
Change your implementation to use the equals() method instead of startsWith().
 if(input.equals("bye")) {
                finished = true;
12
Find the class Random in the Java library documentation.
Which package is it in?
What does it do?
How do you construct an instance? 
Random()
          Creates a new random number generator.
Random(long seed)
          Creates a new random number generator using a single long seed.
How do you generate a random number?
next(int bits) 
Note that you will probably not understand everything that is stated in the documentation. Just try to find out what you need to know. 
OK

13
Try to write a small code fragment (on paper) that generates a random number using this class.

Done
14
Write some code to test the generation of random numbers. To do this create a new class called RandomTester.
In class RandomTester, implement two methods: printOneRandom() (which prints out one random number) and printMultiRandom(int howMany).

Done

15
Find the nextInt() method in class Random that allows the target range of random numbers to be specified. 
intnextInt(int n)
          Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
What are the possible random numbers that are generated when you call this method with 100 as its parameter? 
0 to 99

16
Write a method in your RandomTester class called throwDice() that returns a random number between 1 and 6 (inclusive).


 public int throwDice()
    {
        // initialise instance variables
       Random r;
       r= new Random();
    
       int i = r.nextInt(6)+1;
    
       return i;
  
      
    }
17
Write a method called getResponse() that randomly returns one of the strings "yes", "no" or "maybe".

public void getResponse()
    {
        Random randomGenerator;

randomGenerator = new Random;
 int number = randomGenerator.nextInt(3);
        if (number == 0)
        System.out.println("yes");
        
        if (number == 1)
        System.out.println("no");
        
        if (number == 2)
        System.out.println("maybe");



18
Extend your getResponse() method so that it uses an ArrayList to store an arbitary number of responses, and randomly returns one of them.


public void getResponse()
    {
        ArrayList list = new ArrayList();
        list.add("yes");
        list.add("no");
        list.add("maybe");
        
        int number = generator.nextInt(list.size());
        System.out.println(list.get(number));
    }
19
Implement the random-response solution discussed here in your version of the tech-support system.


OK
20
What happens when you add more (or fewer) possible responses to the responses list?
Will the selection of a random response still work properly?
Why or why not?

doesnt seem any different

21
What is a HashMap?
What is its purpose and how do you use it?
Use the AP Java Subset documentation at the Duke Site.


it matches a key to a value
22
Create a class MapTester. In it, use a HashMap to implement a phone book similar to the example in the text.
Implement the following two methods of class MapTester
        public void enterNumber(String name, String number)
        public String lookupNumber(String name)


public void enterNumber(String name, String number)
    {
        phoneBook.put(name, number);
    }
    
    public String lookupNumber(String name)
    {
        String number = (String)phoneBook.get(name);
        return number;
    }

23
What happens when you add an entry to a map with a key that already exists in the map?


nothing
24
What happens when you add an entry to a map with a value that already exists in the map?


nothing
25
How do you check whether a given key is contained in a map?
26
What happens when you try to look up a value, and the key doess not exist in the map?
returns null
27
How do you check how many entries are contained in a map?


size() method
28
Implement the changes discussed in the text in your own version of the TechSupportsystem.
Test it to get a feel for how well it works.


OK

29
What are the similarities and differences between a HashSet and an ArrayList?
set does not maintain a specific order
list does
in a set each element may be put once
30
The split() method is more powerful than it first seems from our example.
How can you define exactly how a string should be split?
Give some examples.


you choose the index you want to begin the splitting from
31
How would you call the split() method if you wanted to split a string at either space or tabcharacters?
How might you break up a string in which the words are separated by colon (':') characters?
String.split(" ")
String.split(":")

32
What is the difference in result of returning the words in a HashSet compared with returning them in an ArrayList?


sets dont return in a particular order
33
What happens if there is more than one space between words (for example: two or three spaces?
Is there a problem?

nope
34
Read the footnote about the Arrays.asList() method. Find and read the sections in this book about class variables and class methods.
Explain in your own words how this works.
What are examples of other methods the Arrays class provides?
Create a class called SortingTest. In it, create a method that accepts an array of int values as a parameter, and prints out the elements sorted  (smallest element first) to the terminal.

35
Implement the final changes discussed in the text in your own version of the program.
OK





36
Add more word/response mappings into your application. You should copy some out of the solution provided and add some yourself.


OK
37
Sometimes two words (or variations of a word) are mapped to the same response. Deal with this by mapping synonyms or related expressions to the same string, so that you do not need multiple entries in the reponse map for the same response.


OK
38
Identify multiple matching words in the user's input and respond with a more appropriate answer in that case.


OK
39
When no word is recognized, use other words from the user's input to pick a well-fitting default response: for example words like "who","why, "how"

OK
40
Use BlueJ's Generate Documentation function to generate documentation for your techSupport project.
Examine it. Is it accurate?
Is it complete?
Which parts are useful, which are not?
Can you find any errors in the documentation?

41
Find examaples of javadoc key symbols in the source code of the TechSupport project.
How do they influence the formatting of the documentation?


@author
@version


dont reallt influence, just give us information 
42
Find out about and describe other javadoc key symbols.
One palce you can look is the online documentation of Sun Microsystems' java distribution. It contains a documnt called  javadoc - The Java API Documnentation Generator.
In this document the key symbols are called javadoc tags.


Link does not work-page error......

43
Properly document all classes in your version of the TechSupport project.
44
Create a BallDemo object and execute the drawDemo() and bounce() methods.
Then read the BallDemo source code.
Describe, in detail, how these methods work.


the position is changed to make it appear as if it is in motion

45
Read the documentation of the Canvas class. Then answer the following questions in writing, including fragments of Java code.
How do you create a Canvas?

 public Canvas(String title)
 public Canvas(String title, int width, int height)
 public Canvas(String title, int width, int height, Color bgColor)

How do you make it visible?
    public void setVisible(boolean visible)
How do you draw a line?

 public void draw(Shape shape)
    {
        graphic.draw(shape);
        canvas.repaint();
    }
How can you erase something?

 public void erase()
    {
        Color original = graphic.getColor();
        graphic.setColor(backgroundColor);
        Dimension size = canvas.getSize();
        graphic.fill(new Rectangle(0, 0, size.width, size.height));
        graphic.setColor(original);
        canvas.repaint();
    }
What is the difference between draw() and fill()?

 Draw drwas the outline of a given shape onto the canvas as oppose to fill which  Fills the internal dimensions of a given shape with the current 
     foreground color of the canvas.
What does wait do?

Waits for a specified number of milliseconds before finishing.

46
Experiment with Canvas operations by making changes to the drawDemo() method ofBallDemo. Draw some more lines, shapes and text.


Ok
47
Draw a frame around the canvas by drawing a rectangle 20 pixels inside the window borders. Put this functionality into a method called drawFrame() in the BallDemo class.
48
Improve your drawFrame() method to adapt automatically to the current canvas's size.
To do this, you need to find out how to make use of an object of class Dimension.


need help

49
Change the method bounce() to let the user choose how many balls should be bouncing.
50
Which type of collection (ArrayList, HashMap or HashSet) is most suitable for storing the balls for the new bounce() method?
Discuss in writing, and justify your choice.

51
Change the bounce() method to place the balls randomly anywhere in the top half of the screen.
52
Write a new method named boxBounce(). This method draws a rectangle (the "box") on screen, and one or more balls inside the box. For the balls do not use BouncingBall, but create a new class BoxBall that moves around inside the box, bouncing off the walls of the box so that it always stays inside.
The initial position and speed of the ball should be random.
The boxBounce() method should have a parameter that specifies how many balls are in the box.

53
Give the balls in boxBounce() random colors.
54
In class BouncingBall, you will find a definition of gravity. Increase or decrease the gravity value, compile and run the bouncing ball demo again.
Do you observe a change?

55
There is a rumor circulating on the Internet that George Lucas uses a formula to create the names for the characters in his stories:
Your Star Wars first name:
1. Take the first 3 letters of you last name.
2. Add to that the first 2 letters of your first name.
Your Star Wars last name:
1. Take the first 2 letters of you mother's maiden name.
2. Add to this the first 3 letters of the name of the town or city that you were born in.
Create a new BlueJ project named star-wars. In it create a class named NameGenerator. This class should have a method named generateStarWarsName() that generates a Star Wars name using the method described above.
You will need to find out about a method of the String class that generates a substring.

56
The following code fragment attempts to print out a string in upper-case letters:
public void printUpper (String s)
{
        s.toUpperCase();
        System.out.println(s);
}
This code however does not work.
Find out why and explain.
How should it be written properly?

57
Assume we want to swap the values of two integer variables, a and b.
To do this we need to write a method.
public void swap (int i1, int i2)
{
        int tmp = i1;
        i1 = i2;
        i2 = tmp;
}
Then we can call this method with our a and b variables:
        swap(a,b);
Are a and b swapped after this call?
If you test you will notice that they are not!
Why does this not work?
Explain in detail.

58

59

60

61

62