CS46A Lab

Fundamental Types

Copyright Cay S. Horstmann 2009, 2012 Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.

See lab 1 for reporting instructions.

Problems with this icon are optional

  1. Distances
    1. When you are given two points (x1, y1) and (x2, y2) on the plane, the distance between them can be computed according to the following figure:

      Write Java code that computes a variable double distance from variables x1 and x2. Use variables dx and dy, and do not use Math.pow.

    2. In BlueJ, complete this class Distance with your expression and run it with test cases (x1, y1) = (0, 0) and (x2, y2) = (30, 40). What output do you get?
    3. Pick three more test cases: A horizontal line, a vertical line, and a line with a 45 degree angle. What outputs do you get? Why are they correct?
  2. Distances on Earth
    1. Using this site, find the (approximate) longitude and latitude of San Francisco and San Jose. What are they?

    2. This Wikipedia article gives a good overview of computing the distance between two points on Earth. Let's start with the first formula,

      Use this formula to write a program Distance2 that computes the distance between San Jose and San Francisco, keeping in mind the following:

      • Google's angles are in degrees. You must convert the angles to radian. The Math class has a useful method for this.
      • arccos is Math.acos.
      • The formula gives the angular distance. You need to multiply it by the radius of the Earth, which I trust Google will find for you.

      What is your program?

    3. What does it compute for the distance?
    4. What is the distance between San Francisco and New York?
    5. The Wikipedia article claims that the first formula isn't all that good for small distances. Try the Haversine formula and compare the results. What do you get for San Francisco-San Jose and San Francisco-New York with both formulas? Is the Wikipedia article right in stating that the first formula has a higher error?
  3. CodingBat
    1. Task 1
    2. Task 2
    3. Task 3. You need to know how to test a condition: if (str.length() <= 3) return ...; else return ...;

    Paste your answers into the lab report.

  4. Manipulating Strings

    The Exploratorium has a nifty exhibit showing that, according to research at Cambrigde Uinversity, our brain tolerates scrmabled letters in a word when reading text.

    The following exercises explore this scrambling.

    1. Modify the StringScrambler class so that the scramble method returns a word that is made up of
      • the last letter of word
      • all but the first and last letter of word
      • the first letter of word

      For example, if the input is received, the output should be

      deceiver

      Hint: Call substring three times and concatenate (+) the results. What is your program?

    2. Test your program by making an object of type StringScrambler in the BlueJ workbench. Then call the scramble method with an input of resigned. What output do you get?
    3. What happens when you use very short strings, i.e. strings with 2 characters? 1 character? The empty string? Explain your results.
    4. Call scrambleSentence with a sentence of your choice such as "Java programming is easy and enjoyable". Just run it—it calls your scramble method for each word in the sentence.

      What result do you get?

    5. Actually, this scrambling isn't so good. For best results, you should leave the first and last letter alone. Let's change the scramble method so that it scrambles the second and third letter of each word. For example, "word" should get changed to "wrod".

      What is your scramble method now?

    6. Try scrambleSentence again with the same sentence as in step 4. What is the result?
    7. That is better. But it would be even nicer if we could switch any letter with its successor, as long as we leave the first and last character alone. Instead of swapping positions 1 and 2, let's swap positions i and i + 1 where i = randomInt(1, ...).

      The randomInt method has been provided for your convenience.

      What is your scramble method now?

    8. Try scrambleSentence again with the same sentence as in step 4. What is the result?
    9. Almost there. Now pick a random location, but not the first or the last two. Then pick another random location after the first but not the last. Swap those.

      What is your scramble method now?

    10. Try scrambleSentence again with the same sentence as in step 4. What is the result?
  5. Random Walk
    1. Particles move across a plane by a fixed distance, then change direction by turning at a random angle between 0 and 360 degrees, then move again by the same distance, and so on. Intuitively, it would seem that the particles never move very far because all those motions would cancel each other out. This turns out not to be true—it can be shown that the particles travel arbitrary distances, given enough time. We want to model this in Alice. We don't bother with particles and just reuse our car model.

      Unzip the file and move the car directory in a folder sjsu/cs46a/lab5 inside your home directory. (Don't overwrite your old lab project.) Open the project in Netbeans. Rename it to car5 so you don't confuse it with the one from Lab 3.

    2. As before, implement a class Car with a drive method. But this time, your method should have no parameters.
      public class Car extends RedRover
      {
         public void drive()
         {
            move(MoveDirection.FORWARD, ...);
            turn(TurnDirection.LEFT, ...);
         }
      }

      Move the car by two units, then turn it by a random angle (which in Alice is measured between 0 and 1, not 0/360 or 0/2π). Hint: Math.random().

      Be sure to use a named constant for the distance.

      What is the code of your drive method?

    3. Now place the following code in myFirstMethod in the Scene class.
      Car myRover = new Car(50);
      myRover.setVehicle(this); // Needed to make the car appear in the scene
      for (int i = 1; i <= 20; i++)
      {
         car1.drive();
      }

      We'll discuss the loop in chapter 6—it means “run the next statement 20 times”. Just copy/paste it.

      What happens when you run the program?

    4. It's pretty difficult to see where the car has been. Let's do the obvious and drop a cola bottle after every move. Here is how you drop one:
      Prop bottle = new Prop(ColaBottleResource.COLA_BOTTLE);
      bottle.setPositionRelativeToVehicle(getPositionRelativeToVehicle());
      bottle.setVehicle(getVehicle());

      Add these lines to the drive method. Netbeans should complain about not knowing ColaBottleResource. Use Ctrl+Space after that word, or click on the warning icon, to get a list of possible completions/actions. Choose import org.lgna.story.resources.prop.ColaBottleResource. Compile and run. What happens?

    5. Ok, now we can see the trace of the car. But how much did it travel? In myFirstMethod, drop a cola bottle before the car starts moving. Note that you are no longer in a Car method, so you need to call myRover.getPositionRelativeToVehicle() instead of getPositionRelativeToVehicle() etc.

      Mercifully, you don't need to use the Pythagorean theorem in Alice to compute distances. After the 100 steps, compute myRover.getDistanceTo(bottle), where bottle was the initial cola bottle. Have the initial bottle say that distance. (Why not the car? It might be off-screen by now.)

      Note that the say method takes a String parameter, not a double.

      What is the code of your run method?

    6. How much did your car travel when you ran the program?