CS 112
Spring 2023

Old version

This is the CS 112 site as it appeared on May 12, 2023.

Problem Set 2 FAQ

If you don’t see your question here, try Piazza (using its search feature first!) or come to office hours. See the links in the navigation bar for both of those options.

Problem 2

  1. In the material about String objects in Problem 2, you mention that we need to use an equals method to compare two String objects to see if they are equivalent. What about comparisons of char values?

    char values are primitives, so they are compared using the == operator.

  2. Can I concatenate two char values together to get a two-character string?

    No! Because chars are stored as numeric character codes, adding them will produce an integer, not a string.

    For example, assume that we have the following declaration:

    String school = "Boston University";
    

    the expression

    school.charAt(0) + school.charAt(7)
    

    will evaluate to:

    151
    

    because 151 is the sum of the character codes for 'B' and 'U'.

    To fix this, you can include an empty string between the two chars. For example:

    school.charAt(0) + "" + school.charAt(7)
    

    will evaluate to:

    "BU"
    

    This works because as long as at least one of the two operands of the + operator is a string, Java will convert the other operand to a string as needed so that it can perform string concatenation.

Problems 6 and 7

  1. In one of my methods for Problems 6 and 7, I’m getting a StringIndexOutOfBoundsException. What am I doing wrong?

    Don’t forget that the characters in a string have index values that go from 0 to length - 1. The exception means that your code is using an index from outside that range.

  2. Can the methods that we write for Problems 6 and 7 read values from the user?

    No! You should write your methods so that the necessary values are passed in as parameters.

  3. I’m stuck on problem 7, part 3 (remSub). Do you have any additional hints besides the ones mentioned in the assignment?

    We recommend that you start by writing a method that only handles the case in which the second string does occur in the first string. Then, once you have that working, you can add support for the special case in which the second string does not appear in the first string.

  4. I’m stuck on problem 7, part 4 (interleave). Do you have any additional hints besides the ones mentioned in the assignment?

    Here are three:

    • Start by just writing a method that works for the case in which the two strings have the same length. If you can correctly handle that case, you will get most of the credit. Then you can try expanding the method to handle cases in which the strings have different lengths.
    • You will need a loop to build up the portion of the result that includes the interleaved characters. However, you will not need nested loops.
    • Try thinking through the steps needed for concrete values of the parameters. For example, if str1 is "hello" and str2 is "world", how could you gradually build up the value "hweolrllod"?
  5. On problem 7, part 4 (interleave), I’m getting a compiler error when I try to concatenate two characters. For example, the following line gives me an error:

    String combo = ch1 + ch2;
    

    where ch1 and ch2 are chars. What am I doing wrong?

    You can’t concatenate chars. Rather, when you combine two chars using the + operator, you just end up adding their numeric character codes, which gives you a number. In order to concatenate, you need at least one of the two operands to be a String. Thus, in order for the above line to work, you would need to add an empty string so that you will always have at least one String operand:

    String combo = ch1 + "" + ch2;
    

    See the next question for a bit more insight into this issue.

  6. I’m getting strange return values when I test my method for problem 7, part 4 (interleave). Instead of getting letters, I get a string containing numeric digits. For example, StringMethods.interleave("abc", "def") returns "197199201". What am I doing wrong?

    This probably means that you are using the += operator do build up your result. Instead of doing

    result += expr;            // DON'T do this
    

    where the expr is replaced by an appropriate expression, you should instead do the following:

    result = result + expr;    // do this instead
    

    The reason you are getting numbers in the string is because result += expr is equivalent to result = result + (expr), with parentheses around the expression. If the expression involves two characters separated by a + operator, the parentheses will force the characters to get added first, before the concatenation occurs. As a result, you end up adding their numeric character codes together and producing an integer, which is then concatenated to result. For example, consider the following code fragment:

    String str1 = "hello";
    str1 += 'a' + 'b';
    
    String str2 = "hello";
    str2 = str2 + 'a' + 'b';
    

    Both str1 and str2 start out with the string "hello". However, the line

    str1 += 'a' + 'b';
    

    is equivalent to

    str1 = str1 + ('a' + 'b');
    

    which is evaluated as follows:

    str1 = str1 + ('a' + 'b');
         = "hello" + ('a' + 'b')
         = "hello" + (97 + 98)
         = "hello" + 197
         = "hello197"
    

    On the other hand, the line

    str2 = str2 + 'a' + 'b';
    

    does not use +=, and thus no parentheses are added. It is evaluated as follows:

    str2 = str2 + 'a' + 'b';
         = "hello" + 'a' + 'b'
         = "helloa" + 'b' 
         = "helloab"
    
  7. My methods for problems 6 and 7 seem to work, but the compiler is giving me the following error for test code that I’ve added to one of the test programs:

    The method println(boolean) in the type PrintStream is not applicable for the arguments (void)
    

    What am I doing wrong?

    This probably means that you are attempting to print the result of a method call to one of the methods that does not return a value (part 1 of problem 6 or 7). For example, the following lines of code will not work:

    System.out.println(Methods6.printEveryOther("testing"));    // THIS PRODUCES AN ERROR!
    

    You can’t put a method call to printEveryOther inside a println statement, because the method doesn’t return a value. Instead, it does all of the necessary printing itself. To see what it produces, you should simply call the method on its own line. For example, here is how you can fix the line above:

    Methods6.printEveryOther("testing");
    

    Note that the call to printEveryOther is now on its own line, rather than being inside a println statement.

Problem 8

  1. When I try to compile my TerrierShipping program, the compiler is giving me an error message saying that it cannot find one of my variables. Any suggestions?

    Make sure that you declare the variable in a location that gives it a large enough scope.

    For example, here is some code that does not declare the variable val properly:

    int num = console.nextInt();
    if (num < 5) {
        int val = 10;
    } else {
        val = 15;
    }
    

    Note that the variable val is declared inside the block belonging to the if, and thus its scope is limited to that block. As a result, it is not available when we try to use it in the block belonging to the else.

    To fix this code, we need to declare val before the if statement, as follows:

    int num = console.nextInt();
    int val;
    if (num < 5) {
        val = 10;
    } else {
        val = 15;
    }
    
  2. When I try to compile my TerrierShipping program, the compiler is giving me an error message saying that one of my variables might not have been initialized. I’ve tried changing the scope of the variable, but nothing seems to work. Any suggestions?

    This error can result if you initialize a variable inside an if or else block, and then evaluate that variable somewhere else. For example:

    int var;
    if (some condition) {
        var = 5;
    }
    System.out.println(var);
    

    The compiler is pointing out that if the condition is not true, then the variable will not be assigned a value – and thus the println statement will fail.

    In order to eliminate this error, you need to make whatever changes are necessary to ensure that the variable will always be assigned a value before it is evaluated. For instance, we could fix the above example in one of two ways:

    1. assign an initial, default value when the variable is declared:

      int var = 3;
      if (some condition) {
          var = 5;
      }
      System.out.println(var);
      
    2. add an else clause that assigns a value to var when the condition is not true:

      int var;
      if (some condition) {
          var = 5;
      } else {
          var = 3;
      }
      System.out.println(var);
      
  3. When I try to compile my TerrierShipping program, the compiler is giving me an error message saying that one of my methods is missing a return statement. It looks to me like I have all of the return statements I need. What am I doing wrong?

    This error can result if all of your return statements are in if or if-else blocks. For example:

    public static int getVal(int valType) {
        if (valType == 1) {
            return 3;
        } else if (valType == 2) {
            return 5;
        }
    }
    

    The compiler will complain, because if neither (valType == 1) nor (valType == 2) is true, then the method will not return a value.

    In order to eliminate this error, you should make sure that one of your return statements is outside an if or if-else blocks. In the example above, changing the else if to an else would do the trick:

    public static int getVal(int valType) {
        if (valType == 1) {
            return 3;
        } else {
            return 5;
        }
    }
    
  4. In my TerrierShipping program, I have an if-else if statement that I’m using to determine which value to use, but it always uses the value from the else block, regardless of which choice the user specifies. What am I doing wrong?

    One possible explanation is that you may be trying to compare strings using the == operator. This won’t work, because strings are objects, and the == operator does not correctly compare objects. Instead, you need to use a method (the equals method) to compare the strings. For an example of this, see the way that the starter code we provided in main checks for the case in which the user enters the string "Q".

  5. In my TerrierShipping program, I’ve written a method that returns a value. However, that value doesn’t seem to be available in the main method after the method returns. Any suggestions?

    Make sure that you aren’t throwing away the return value. For example, here is an incorrect version of a line from the beginning of the do-while loop in the main method.

    getItemType(console);     // XXX: incorrect
    

    Note that the method call to getItemType throws away its return value, because it isn’t used in any way.

    Here is the correct version:

    String itemType = getItemType(console);     // XXX: incorrect
    

    In this version, the return value of the method call replaces the method call and is assigned to the variable itemType, so that the value can be used later on in the main method.

    You should do something similar when you call a method that returns a value.

    (By the way, it’s worth noting that although the getItemType method uses a variable called itemType to store the string entered by the user, this is a completely separate variable from the variable itemType in the main method. Therefore, we still need to have the method return the item type, and we need to use that return value in some way in the main method.)

  6. In my program, I’m trying to increment the value of one variable by the value of another variable. However, it doesn’t seem to be working. Any suggestions?

    If you are using the shortcut += operator, make sure that you have the + and the = in the correct order.

    val += num will increment the value of val by the value of num.

    On the other hand, val =+ num (with the = coming before the +) will simply assign the value of num to val.

  7. Part of my program doesn’t do what it’s supposed to do, and I can’t figure out why. Any suggestions?

    You need to perform some debugging! In other words, you need to step through your program to see how the values of your variables are changing and where your logic errors are.

    There are at least two ways to do this:

    1. Add temporary println statements at various points in the problematic piece of code (e.g., inside each loop). Use these println statements to print the values of the key variables so that you can see how they change over time. Note that you can also print out the value of an expression (e.g., val < 100) to see how it changes over time.
    2. Step through the problematic code “on paper”. Make a table for the key variables, and use it to keep track of their values (as well as any outputs) as you “execute” the statements in the same order that the interpreter would use.