CSCI 241 Labs: Lab 11

CSCI 241 Labs: Lab 11
Where is My Variable?


Read all of these instructions before beginning the exercises. There are 6 checkpoints total in this lab. You and your partner should work together using just one of your accounts. Make sure each partner understands the exercises as you progress. If you need help with any exercise, raise your hand.

Copy the Lab11 directory from the course directory to your account. It contains all the Java code you will need for this assignment. If you have forgotten how, refer to the materials for either Lab 1 or Lab 2.

For the first exercises in this lab, you and your partner will need some paper and a pen or pencil.

 

Class, Instance and Local Variables

Work through the following two programs by hand with your partner and predict the output. Write down your predictions!

Puzzle 1

public class Foo   {
    private static int xx = 0;
    private int yy;

    public Foo () {
         xx = 2;
         yy = 3;
    }

    public Foo (int first, int second) {
         xx = first;
         yy = second;
    }

    public void init () {
        System.out.println( "xx = " + xx);
        System.out.println( "yy = " + yy);
    }

    public static void main ( String [] args )    {
       Foo foo1 = new Foo();
       Foo foo2 = new Foo(7, 17);

       foo1.init();
       foo2.init();

       System.out.println( "done");
    }
}

 

Puzzle 2

public class Strange	{
   private int x;

   public Strange ()   {
      x = 34;
   }

   public int doSomething (int x)   {
      System.out.println ("Inside doSomething, x = " + x);
      x = x + 1;
      System.out.println ("After increment, x = " + x);
      return x;
   }

   public int getStrangeValue ()   {
      return x;
   }
   
   public static void main ( String [] args )   {
      int x = 6;
      Strange s1 = new Strange();
      Strange s2 = new Strange();

      x = s1.doSomething(10);
      x = s2.doSomething(20);

      System.out.println("in main(), x = " + x);
      System.out.println("s1 has value " + s1.getStrangeValue());
      System.out.println("s2 has value " + s2.getStrangeValue());
    }
}

Change directories into Lab11 and start BlueJ by entering bluej&. Open the project Puzzles, then compile and run the main() method in the Foo class. Was your prediction correct?

Compile and run the main method in the Strange class. How was your prediction for that one?

1 Show us the output that you had predicted for each program. Be prepared to tell us if and where part of the code tricked you, and explain the output of the program.

Close project Puzzles.

 

Implementing and Testing the Class Constants and Methods

Open the ThermometerProject. Examine the implementation of the Thermometer class to see what it currently contains. Create a new class in this same project, and call it Test. Within Test, write a class method main() that will print out the value of each public class constant that you see in the Thermometer class. Hint: BlueJ allows you to copy and paste lines from one class to another. Use this feature to help avoid mistakes from mistyping the long constant names!

Back to the Thermometer class!
Add two public class methods to translate fahrenheit-to-celsius and celsius-to-fahrenheit. Create the two methods:

  1. fahrenheitToCelsius()
    takes one double as a parameter which holds a number of degrees in the fahrenheit scale. It will calculate the equivalent celsius value and return it as a double.
  2. celsiusToFahrenheit().
    takes one double as a parameter which holds a number of degrees in the celsius scale. It will calculate the equivalent fahrenheit value and return it as a double. take one double as a parameter and return a double.
As you write your methods, make certain to use the constants defined in the class rather than "hard code" those values. Refer to the prelab for the appropriate formulas for the methods.
2 Show us your finished program. Be prepared to answer the following questions:
  1. You didn't have to make an instance of the Thermometer class to print the constants. Why not?
  2. Show us how you implemented each of the two class methods and show us your test cases.

 

Implementing the Constructors

So far, all your coding has involved class variables and methods. Every thermometer has its own temperature though, right? Locate the declaration of the instance variable in the Thermometer class. Next, you'll write multiple constructors to set it.

Write two constructors for the Thermometer class:

The class already contains "getters" and "setters" for the instance variable. Complete the "fahrenheit" ones for the next checkpoint:

  1. getFahrenheit()
    should call a class method to help it do the conversion.
  2. setTemperatureUsingFahrenheit()
    should call a class method to help it do the conversion.
Note: these methods are short! Any method you write whose body is more than four lines long is being done incorrectly.

Your instructors have supplied a separate class to test these methods. Once you are done implementing the methods, compile and run the InstanceTest class. Carefully examine the output to make certain all the tests have passed.

3 Show us the output from the InstanceTest run. Be prepared to answer the following questions:

  1. Why are there only two constructors? In particular, why don't we implement a constructor that takes an initial Fahrenheit temperature?
  2. There is a way to call one constructor from another one, which is explained in Chapter 9. What would be a good reason why a programmer would call one constructor from another?
  3. Why did we make currentTemperature an instance variable rather than a class variable?
Close the ThermometerProject project.

 

Back to the Point Class

In a previous lab (#10) we used an instantiable class named Point. For the next couple of checkpoints, you'll work with a new version of this class and add more features to it.

Don't copy your old code! Open the PointIn2D project. This contains most of the completed code for all of the exercises we did in that lab.

Your first job is to add a couple of methods to this class that we didn't get to the first time around:

  1. Complete the second version of the distanceTo() method, which has this signature:
    public double distanceTo(Point p2)
    This method should calculate and return the same information as the already-written version of the method.
  2. Write an equals()method to see if the current Point is the same as the one in the parameter. Here is its signature:
    public boolean equals(Point p2)
    This method should return true when the two Point objects have the same values in their instance data, otherwise false.
To test these methods, create objects on BlueJ's object bench for 2 points. Name them "p1" and "p2" (rather than taking BlueJ's default names). Once objects have been created there, you can type p1 or p2 as parameter values whenever methods you wish to run require objects as parameters. Try it!

4 Show us the code you wrote for the above changes and how you tested your new methods. Answer these questions:

  1. How did you get the values of xCoord and yCoord for the parameter object in your new methods?
  2. Of the two distanceTo() methods in your program, which one better reflects data encapsulation?
  3. You wrote a method named equals() to see if two Point objects are the same. What is compared when we use == between two Point objects?

Finding the Midpoint

Another easy calculation to do with points is to find the midpoint between two points. Its formula is simple: if we have two points named p1 and p2:
Add an instance method to your class named public Point findMidpoint(Point p2). It should calculate the midpoint between the current point and that of the parameter. It will create a Point with those values and return it.

Draw state-of-memory diagrams to describe what is happening in this method. When finished, compile and run the TestPoint class main() method. Enter values you can calculate easily to test your results.

You can see that there is already a class method written that tries to do this: public static void findMidpoint(Point,Point,Point), but it is commented out. Code to test it in the main() method is also commented out. That's because it doesn't work!

Draw a state-of-memory diagram of what is going on in the method calls to help you figure things out.

Uncomment the code in both classes related to this method and run it to see what the difference is between what you wrote and what the static method produces for results.

Work with your partner to diagnose the problem and fix it so that it will work correctly. Note: Do NOT change the return type or the parameters, only make changes to the method body.

5 Show us the code you wrote, and answer these questions:

  1. When you create and return a Point object inside your findMidpoint() method, what is actually returned: the object itself (with all its contents), or the memory address of that object?
  2. What was the problem with the class method?
  3. Which seems to better model finding midpoints: the instance method or the class method?

 

Extras for Experts

Some modern thermometers keep track of maximum and minimum temperatures. Implement these in your thermometer class. It will require two extra data members, maximumTemp and minimumTemp, plus two additional "getters". You will not write new "setters", instead modify the ones you have.

 

After the Lab

Don't forget to exit Firefox before you log out.

6 Show us that you have logged out, turned off your monitor, cleaned up, and pushed in your chairs for this last checkpoint.