CS46A Lab

Fundamental Types

Copyright © Cay S. Horstmann 2009 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.

      Make a new Alice project car2 in Netbeans. Load car.a3p and be sure that your project is called car2 so that you don't overwrite your old lab project.

    2. In the MyCar class, implement a method
      public void drive()
      {
         move(MoveDirection.FORWARD, ..., ...);
         turn(TurnDirection.LEFT, ..., ...);
      }

      that drives the car by two units, then turns 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. The move and turn methods have a third parameter to give the duration of the animation. Set the duration to SHORT, a constant that you should define in the method and set to 0.05.

      What is the code of your drive method?

    3. Now place the following code in the MyScene.run method:
      for (int i = 1; i <= 100; i++)
         car1.drive();

      We'll discuss the loop in chapter 6—it means “run the next statement 100 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 toaster after every move. Here is how you drop a toaster:
      Toaster t = new Toaster();
      t.setLocalPointOfView(getLocalPointOfView());
      getScene().addComponent(t);

      Add these lines to the drive method. Netbeans should complain about not knowing Toaster. Ctrl+Space tells NetBeans to “cheat” and give you a list of possible completions/actions. Try it out to get a feel for it: Type Toaster, then Ctrl+Space, or perhaps Toaste, then Ctrl+Space. Caution: This feature is addictive, and once you are hooked, you'll have a hard time going back to BlueJ. (If you can't figure out how to use Ctrl+Space, import the package org.alice.apis.moveandturn.gallery.kitchen.Toaster, but be sure to have someone else show you later.) Compile and run. What happens?

    5. Ok, now we can see the trace of the car. But how much did it travel? In the MyScene.run method, drop a toaster before the car starts moving. Note that you are no longer in a MyCar method, so you need to call car1.getScene() instead of getScene etc.

      Mercifully, you don't need to use the Pythagorean theorem in Alice to compute distances. After the 100 steps, compute car1.getDistanceTo(t), where t was the initial toaster. Have the car say that distance. (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?