CS 112
Spring 2018

Old version

This is the CS 112 site as it appeared on May 11, 2018.

Lab 1: Getting started

FLR 267

If your lab meets in FLR 267, you should begin by following the instructions found here.

Using folders

We strongly encourage you to create a separate folder for each lab and each problem set, so that you can more easily keep track of your work. For example, you could create a folder called lab1 for your work on this lab, and put all of the files for this lab in that folder. If you are working on a lab machine, you will need to create the folder on the Z: drive, so that it won’t be lost when you log out.

Task 0: Review lab policies

Note

You cannot get credit for completing the lab tasks at home and coming to lab only to sign the attendance sheet.

Task 1: Piazza

We are using Piazza for online course discussion. If you haven’t set up an account yet, do that now. If you have set up an account, go ahead and log in. In either case, you should use the Piazza link in the navigation bar of the course website.

There are some helpful features of Piazza that we would like to emphasize:

Task 2: DrJava basics

In Lab 0, you should have installed DrJava, which is the environment that we’re recommending for your work in CS 112.

To see how to use it, let’s take the following steps together:

  1. Start up DrJava, either on your lab computer or on your own machine. If you have trouble finding the program, please let us know.

  2. If you haven’t already done so, select the Preferences option from the Edit menu in DrJava and do the following:

    • Click on Display Options in the Categories pane and make sure that the checkbox for Show All Line Numbers is checked.
    • Click on Miscellaneous option in the Categories pane and change the Indent Level setting to 4.
    • If the default fonts are too small, click on Fonts in the Categories pane and change the fonts so that the sizes are larger. Important: For the Main Font, you should use a fixed-width font in which each character has the same width. Options include Lucida Console and Courier New.
    • Click Apply, then click OK.
  3. Download the file Task2.java, putting it in the folder that you created for this lab. (Remember that if you are working on a lab machine, you should store things in your Z: drive.)

  4. Open the file in DrJava.

  5. You’ll notice that the code we’ve provided has extremely poor indentation. Dr. Java makes it easy to fix our indentation by doing the following:

    • Press CTRL-A to select all of the code.
    • Press the Tab key.
  6. Compile the program by clicking the Compile button near the top of the screen.

  7. Run the program by clicking the Run button, which will display the text printed by the program.

Task 3: Simple debugging

Now let’s see how the basic debugging process works in DrJava.

  1. Add the following (buggy) method to the program from Task 2:

    /*
     * triArea - computes and returns the area of a triangle 
     * with base b and height h (both of which are integers).
     * The area is returned as a floating-point number, and 
     * the result should be as precise as possible.
     */
    public static double triArea(int b, h) {
        area = b/2 * h;
        return area
    }
    

    Cut and paste the method inside the class Task2 – either before or after the main method.

    Use CTRL-A followed by Tab as needed to fix the indenting.

  2. Try compiling the program again. You should see 2 errors:

    • identifier expected - this one stems from the way that the parameters of the method are defined. Do you see the problem?

    • ; expected - this one is more obvious!

  3. Note that initially the first error message is highlighted in yellow, along with the line of code that is most likely to have caused the error (line 16).

    Click on the second error message, which will highlight the message and its associated line of code (line 18).

  4. Fix the two errors. Feel free to ask for help as needed!

  5. Compile again. Unfortunately, you’ll see that fixing the original bugs has revealed a new one!

  6. Continue fixing bugs and recompiling until you see the message

    Compilation completed.
    

    This means that all of our syntax errors have been fixed. However, there may still be logic errors in the new method, and to find them we need to perform some testing!

  7. One way to test a static method is to use DrJava’s Interactions Pane. Click on the tab labeled Interactions near the bottom of the window, which should display this prompt:

    >
    

    This prompt is like the >>> prompt in the Python Shell, and you can use DrJava’s Interactions Pane in much the same way that you use the Shell in Python. For example, you can evaluate an expression:

    > 3 + 5 * 2
    13
    
  8. Once our code compiles, we can make test calls to our static method from the prompt. Because these calls are being made from outside the class to which the method belongs, we need to prepend the class name. For example:

    > Task2.triArea(10, 3)
    15.0
    

    This result is correct, because the area of a triangle with base 10 and height 3 is indeed 15.0.

  9. However, one test is almost never good enough! What do you get when you try this call?

    > Task2.triArea(9, 3)
    

    Hint: To save yourself some typing, use the Up arrow to go back to the previous expression, and edit it to create the new call.

    You should see that this call returns 12.0. However, the actual area of a triangle with base 9 and height 3 is 13.5.

  10. To fix this logic error, we need to realize the following:

    • Java’s / operator is used for both integer division and floating-point division.

    • If both of the operators are integers, / performs integer division, which truncates the digits after the decimal. This is what is happening when we compute b/2.

    • In order to get floating-point division — which preserves the digits after the decimal — we need to make sure that at least one of the operands is a floating-point number.

    Go ahead and make the change needed to get floating-point division.

  11. Recompile the code. Note that you must recompile after any change to your code.

  12. Try the test call again, to ensure that it works:

    > Task2.triArea(9, 3)
    13.5
    

Task 4: Strings and their methods

Open up a text editor (e.g., Notepad or TextEdit) and create a [plain-text file][pt] named lab1task4.txt. Put all of your work for this problem in that file.

In Problem Set 1, there are several problems in which you will need to work with String objects in Java.

It turns out that Java lacks many of Python’s built-in operators and functions for strings. Instead, most operations involving strings – including indexing and slicing – are done using methods that are inside the string object.

The table below (which also appears in Problem Set 1), compares the ways in which some common string operations would be accomplished in Python and Java:

operation

in Python

in Java

assigning to a variable (and, in Java, declaring the variable)

s1 = 'Boston'
s2 = "University"

String s1 = "Boston";
String s2 = "University";

concatenation

s1 + s2

s1 + s2

finding the number of characters

len(s1)

s1.length()

indexing
(note: Java does not have negative indices)

s1[0]
s2[-1]

s1.charAt(0)
s2.charAt(s2.length()-1)
(see the notes below the table for a key fact about this method)

slicing

s1[1:4]
s2[3: ]
s1[ :5]

s1.substring(1, 4)
s2.substring(3)
s1.substring(0, 5)

converting all letters to uppercase

s1.upper()

s1.toUpperCase()

converting all letters to lowercase

s2.lower()

s2.toLowerCase()

determining if a substring is in a string

s2 in s1
'sit' in s2

s1.contains(s2)
s2.contains("sit")

finding the index of the first occurence of a character or substring

s1.find("o")
s2.find('ver')

s1.indexOf('o')
s2.indexOf("ver")

testing if two strings are equivalent

s1 == s2
s1 == 'Boston'

s1.equals(s2)
s1.equals("Boston")

Additional notes:

Given the information above, here are the tasks you should perform:

  1. To ensure that you understand how the above string operations work in Java, use the Interactions Pane to enter the statements and expressions from the Java column of the table above. Make sure to begin with the first lines in that column, so that you will declare and assign values to the variables s1 and s2.

    In addition to the expressions in the table, try other variations of those expressions until you are confident that you understand how the methods and operators work.

  2. To facilitate your remaining work on this task, here’s a reminder of the two string variables that you initialized at the start of the task:

    String s1 = "Boston";
    String s2 = "University";
    

    Test that these variables still have their values by entering each variable from the Interactions Pane:

    > s1
    "Boston"
    > s2
    "University"
    

    If for some reason the variables don’t have these values, go ahead and reinitialize them in the Interactions Pane.

  3. We’re now going to solve a series of puzzles in which we construct an expression involving operations on s1 and/or s2 to produce a specified target value.

    For example, let’s say that we want to construct an expression involving s1 or s2 that produces the following value:

    "ton"
    

    One possible expression that works for this puzzle is s1.substring(3, 6). We can test that it works in the Interactions Pane:

    > s1.substring(3, 6)
    "ton"
    
  4. Now solve the puzzles below, and put the expressions in your lab1task4.txt file.

    1. Construct an expression involving s1 or s2 that produces the following value:

      "Uni"
      
    2. Construct an expression involving s1 or s2 that produces the following value:

      "UNI"
      

      Hint: Chain two method calls together. For example:

      > s1.toLowerCase().substring(0, 3)
      "bos"
      
    3. Construct an expression involving s1 or s2 that produces the following value:

      'v'
      

      Note that the single quotes mean that you must produce a char, not a String. See the notes under the table above that discuss the char type.

    4. Construct an expression involving s1 or s2 that produces the following value:

      "STONE"
      

Task 5: Writing static methods

This task asks you to write a series of static methods.

Begin by downloading this file: Task5.java. Open it in DrJava, and add your methods to the class that we have given you in that file.

  1. a static method called print3Times that takes a string as its parameter and prints it three times. For example:

    > Task5.print3Times("hello")
    hello
    hello
    hello
    

    We have given you this example method in the starter file.

    One thing worth noting: the header of the method has the word void in it. Make sure you understand what that means, and ask us if you’re not sure.

  2. a static method called printNTimes that takes an integer n and a string (in that order) as its parameters and prints the string n times. For example:

    > Task5.printNTimes(5, "hello")
    hello
    hello
    hello
    hello
    hello
    > Task5.printNTimes(2, "hello")
    hello
    hello
    
  3. a static method called replaceStart that takes two strings s1 and s2, and does the following:

    • If the length of s1 (call it s1Len) is less than the length of s2, the method returns a string in which the first s1Len characters of s2 are replaced by s1. For example:

      > Task5.replaceStart("abc", "xxxxxxx")
      "abcxxxx"
      > Task5.replaceStart("hello", "xxxxxxx")
      "helloxx"
      
    • If the length of s1 is greater than or equal to the length of s2, the method just returns s1.

      > Task5.replaceStart("hello", "bye")
      "hello"
      

Extra Practice!

If you get through the exercises above, congratulations!

For extra practice, you can try some exercises from an excellent site called Practice-It.

Task 6: Submit your work

You should use Apollo to submit the following files:

Don’t worry if you didn’t finish all of the tasks. You should just submit whatever work you were able to complete during lab.

Warnings

  • Make sure to use these exact file names, or Apollo will not accept your files. If Apollo reports that a file does not have the correct name, you should rename the file using the name listed in the assignment or on the Apollo upload page.

  • Make sure that you do not try to submit a .class file or a file with a ~ character at the end of its name.

  • Before submitting your files, make sure that your BU username is visible at the top of the Apollo page. If you don’t see your username, click the Log out button and login again.

  • If you make any last-minute changes to one of your Java files (e.g., adding additional comments), you should compile and run the file in DrJava after you make the changes to ensure that it still runs correctly. Even seemingly minor changes can cause your code to become unrunnable.

  • If you encounter problems with Apollo, close your browser and try again. If possible, you may also want to wait an hour or two before retrying. If you are unable to submit and it is close to the deadline, email your homework before the deadline to cs112-staff@cs.bu.edu

Here are the steps:

  1. Login to Apollo, using the link in the left-hand navigation bar. You will need to use your Kerberos user name and password.
  2. Check to see that your BU username is at the top of the Apollo page. If it isn’t, click the Log out button and login again.
  3. Find the appropriate lab section on the main page and click Upload files.
  4. For each file that you want to submit, find the matching upload section for the file. Make sure that you use the right section for each file. You may upload any number of files at a time.
  5. Click the Upload button at the bottom of the page.
  6. Review the upload results. If Apollo reports any issues, return to the upload page by clicking the link at the top of the results page, and try the upload again, per Apollo’s advice.
  7. Once all of your files have been successfully uploaded, return to the upload page by clicking the link at the top of the results page. The upload page will show you when you uploaded each file, and it will give you a way to view or download the uploaded file. Click on the link for each file so that you can ensure that you submitted the correct file.