Monthly Archives: March 2014

Java String Loops 2

public int countF(String str)

Description: This method returns the number of times that the letter ‘f’ occurs in str.

Method Call return value/output
countF(“abcdef”) 1
countF(“abcdfef”) 2
countF(“fff”) 3
countF(“xxx”) 0

 

public boolean has2Fs(String str)

Description: This method returns true if str has exactly two occurrences of the letter ‘f’ in it.

Method Call return value/output
has2Fs(“foo”) false
has2Fs(“fofo”) true
has2Fs(“foffo”) false

 

public boolean has2Fs3Gs(String str)

Description: This method returns true if str has exactly two occurrences of the letter ‘f’ in it and 3 occurences ‘g’.

Method Call return value/output
has2Fs3Gs(“foog”) false
has2Fs3Gs(“foggfog”) true
has2Fs3Gs(“foffoggg”) false

public int momOrDad(String str)

Description: This method returns the number of times that the String “mom” or the string “dad” occurs in the parameter str .

Method Call return value/output
momOrDad(“foog”) 0
momOrDad(“momf”) 1
momOrDad(“momdadmo”) 2
momOrDad(“momdadmom”) 3

 

public String threeTimes(String str)

Description: This method returns the String str concatenated with itself three times

Method Call return value/output
threeTimes(“foog”) “foogfoogfoog”
threeTimes(“abc”) “abcabcabc”
threeTimes(“zt”) “ztztzt”
threeTimes(“”) “”

 

public String nTimes(String str, int n)

Description: This method returns the String str concatenated with itself n times

Method Call return value/output
nTimes(“fg” , 2 ) “fgfg”
nTimes(“abc” , 0 ) “”
nTimes(“zt” , 3 ) “ztztzt”
nTimes(“uiz” , 4 ) “uizuizuizuiz”

 

 

public String countMiddleChar(String str)

Precondition: str.length() ≥ 3.

Description: This method returns the number of times the middle letter of str appears in str.

Method Call return value/output
countMiddleChar(“acbcb” ) 2
countMiddleChar(“acbcx” ) 1
countMiddleChar(“bbbbb” ) 5
countMiddleChar(“xytbtzy”) 1

 

 

public int indexOf(String haystack, String needle)

Description: Write your own indexOf() method. Obviously, you cannot make use of the String’s build in indexOf() method. This method returns the index of the first occurrence of needle in haystack . (Full credit if you can get this to work with Strings whose length is greater than 1).

Method Call return value/output
indexOf(“acxb”, “x” ) 2
indexOf(“zazt”, “z” ) 0
indexOf(“tayv”, “g” ) -1
indexOf(“hijklj”, “j” ) 2

If you want the extra credit, then it must also be able to complete the following example calls

Method Call return value/output
indexOf(“acxb”, “cx” ) 1
indexOf(“acxb”, “cxb” ) 1
indexOf(“acxb”, “cxbt” ) -1

 

public int countChars(String str, String chars)

Precondition:The length of chars is less than or equal to the length of str

Description: This method returns the number of times that charsoccurs in String str.

Method Call return value/output
countChars(“momdadmom” , “dad” ) 1
countChars(“foobofoo” , “foo”) 2
countChars(“foobofoofoo” , “foo”) 3
countChars(“foobofoofoo” , “xy” ) 0

Java String Loop Assingments 1

 

public void printTwos(String str)

Description: This method prints two letters from the String starting at with the first two letters and ending with the last two.

Method Call return value/output
printTwos(“abcdef”) “ab”
“bc”
“de”
“ef”

 

 

public void printReverse(String str)

Description: This method print every letter in reverse and on a new line.

Method Call return value/output
printReverse(“abcd”) “d”
“c”
“b”
“a”
printReverse(“thefoo”) “o”
“o”
“f”
“e”
“h”
“t”
public void printTwoReverse(String str)

Description: This method print every 2 letter in reverse and on a new line.

Method Call return value/output
printTwoReverse(“abcd”) “dc”
“cb”
“ba”
printTwoReverse(“thefoo”) “oo”
“of”
“fe”
“eh”
“ht”

 

public void printTwoReverseAgain(String str)

Description: This method print every 2 letter in reverse and on a new line and with no overlap of letters

Method Call return value/output
printTwoReverseAgain(“abcd”) “dc”
“ba”
printTwoReverseAgain(“thefoo”) “oo”
“fe”
“ht”

 

 

Gridworld Bug Subclasses

 SlowBug class

A SlowBug is a Bug that poops Rocks instead of Flowers when it moves. However, since Rocks take a little bit longer to get out than Flowers do, a SlowBug takes THREE timesteps (three calls to act) before it is able to move like a normal bug .

A SlowBug is a Bug has the following behaviors and attributes:

  • a SlowBug has an instance variable called counter that is increased each time it acts
  • the default constructor for this class will set the bug’s color to green.
  • It also has a constructor that takes a color parameter :

    public SlowBug(java.awt.Color col)

  • After a SlowBug has waited two turns without doing anything, it acts exactly like a normal bug..
    At the end of each act, whether or not the bug has done anything, it increments counter variable.
  • the move method works the exact same as a regular Bug’s move, except instead of pooping a Flower in the space it leaves, it poops a Rock the same color as itself.

If you want, you can download SlowBug.gif and drag it into Eclipse or Bluej to use that image instead of the default Bug image.
The final result of running SlowBug would be something like the picture below.

 

FastBug

    FastBug is exactly like a normal bug, except it acts twice each “timestep” instead of just once. For example, in one timestep it will:

  • check if it can move, and if it can, it will move. If it can’t it will turn.
  • After it moves or turns, it will check if it can move again, and if it can, it will move. If it can’t, it will turn.

A FastBug is a Bug and should contain the following behaviors:

  • the default constructor for this class will set the bug’s color to red. It should also make it start out in a random direction (not always facing North like a normal bug does).
  • the act method should behave as described above
  • a FastBug is so fast, the flowers it leaves behind are already almost wilted when they come out. To do this, you will need to modify the move method so that the Flower it generates is not the same color as the FastBug, but five “shades” darker. To increase the darkness, use the Color class’s non-static darker()method five successive times on your color before passing it in to the Flower constructor.

If you want, you can download FastBug.gif and drag it into Eclipse to use that image instead of the default Bug image.

 

If you want an A, you must do FIsh:

Fish

Last year’s Marine Biology Case Study was similar to GridWorld, but it worked with Fish objects that have a 1/7 chance of breeding (or, more accurately, spontaneously generating children) each timestep and a 1/5 chance of dying each timestep. A Fish cannot move backwards, and our Fish will not turn, move, or generate children diagonally; it will only use the 4 cardinal directions North, South, East, and West. For this part of the lab, we are going to create a similar Fish in GridWorld.

A Fish is an Actor and should contain the following behaviors and attributes:

  • a shared, static instance variable: private static int nextAvailableID = 1; 
    A static variable is one that ALL instances of the class share. So the first fish that is made will initialize the static variable to 1; the others will keep using it.
  • a private int instance variable: private int myID;
  • a private static double instance variable for probabilityOfBreeding that is initialized to 1.0/7.0 and a private double instance variable for probabilityOfDying that is initialized to 1.0/5.0
  • Also, your fish should not die during the first 5 steps of the program.
  • the default constructor for this class should
    • set the Fish’s color to a random color. Use (Math.random()*256)typecast as an int to get random numbers between 0 and 255 for the Color constructor.
      • import java.awt.* to be able to initialize a new Color(double r, double g, double b);where r,g,b are each ints between 0 and 255 inclusive and represent the red, green and blue values of the color
    • The constructor should also make the Fish start out in a random direction (from North, South, East, or West…no other directions are allowed for a Fish). In the constructor, set      myID=nextAvailableID++;
      This means the first fish will get the ID 1, the next will get 2, the next will get 3, etc. Since nextAvailableID is static, it is shared amongst all fish.
  • override the public String toString() method as follows:
    public String toString()
    {
        return myID + " facing " + getDirection();
    }
  • protected boolean breed() method should be written that:
    • First calls Math.random() and checks to see if the number is the random number generated is >= probabilityOfBreeding. If it is, return false (your Fish did not breed this time).
    • Otherwise, if the random number was < probabilityOfBreeding, that means we will try to breed in all the empty locations in front, behind, to the left, and to the right of us.
      To do this, first find out how many empty locations you have above you, to your right, to your left, and below you.

      • If you have zero empty spaces above you, to your right, to your left, and below you, return false (you didn’t have an open space to generate children to so you couldn’t breed).
      • If you have one to four empty spaces, you will need create new Fish objects, then have them place themselves in the empty locations. When you are finished generating all the children you can, return true (you successfully bred).
  • protected void move() method should be written that:
    • checks for all valid, empty spaces above you, to your right, and to your left (Fish don’t move backwards, so we don’t check below you), then picks one of those to move to and goes there, changing directions to face the spot you are moving to (for instance, if you are going to an empty spot to your left, you turn left after you go there). If there are no empty locations you can go to, just stay still.
      Note: If you look through the GridWorld API in the Location class and Grid interface, you will find some methods very helpful in writing this method.
  • the act method should be overridden with the following code:
    public void act()
    {
    // Try to breed.
    if ( ! breed() )
    move(); 
    // Did not breed, so try to move.// Determine whether this fish will die in this timestep.
    if ( Math.random() < probabilityOfDying )
    removeSelfFromGrid();
    }

If you want, you can download Fish.gif and drag it into Eclipse to use that image instead of the default Actor image.
It can be kind of hard to tell what is happening, but if you move your mouse over a Fish in the grid you can see the toString() printed out, which will tell you which unique fish id you are looking at. Since breeding, dying, and moving are random, there is no set way to guarantee what your grid will look like, but here is how mine looked after it ran a few times

 

while-if-elif-else Jeroo[Python]

Assignment  if_elif_else_while_D  

  • start at  (0,0)
  • end at (0,23)
  • use 1 loop
  • pick up the 1 flower and use the following while loo

Use this code at the start of your program

 

The map

if_elif_else_while_D_BEFORE

What the map and Jeroo looks like at the completion of the loop

if_elif_else_while_D_AFTER_2