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
-
In the material about
Stringobjects in Problem 2, you mention that we need to use anequalsmethod to compare twoStringobjects to see if they are equivalent. What about comparisons ofcharvalues?charvalues are primitives, so they are compared using the==operator. -
Can I concatenate two
charvalues 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
151is 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
-
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.
-
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.
-
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.
-
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
str1is"hello"andstr2is"world", how could you gradually build up the value"hweolrllod"?
-
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
ch1andch2arechars. What am I doing wrong?You can’t concatenate
chars. Rather, when you combine twochars 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 aString. 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 oneStringoperand:String combo = ch1 + "" + ch2;
See the next question for a bit more insight into this issue.
-
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 doingresult += 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 += expris equivalent toresult = 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 toresult. For example, consider the following code fragment:String str1 = "hello"; str1 += 'a' + 'b'; String str2 = "hello"; str2 = str2 + 'a' + 'b';
Both
str1andstr2start out with the string"hello". However, the linestr1 += '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" -
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
printEveryOtherinside aprintlnstatement, 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
printEveryOtheris now on its own line, rather than being inside aprintlnstatement.
Problem 8
-
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
valproperly:int num = console.nextInt(); if (num < 5) { int val = 10; } else { val = 15; }Note that the variable
valis declared inside the block belonging to theif, 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 theelse.To fix this code, we need to declare
valbefore theifstatement, as follows:int num = console.nextInt(); int val; if (num < 5) { val = 10; } else { val = 15; } -
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
iforelseblock, 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:
-
assign an initial, default value when the variable is declared:
int var = 3; if (some condition) { var = 5; } System.out.println(var); -
add an
elseclause that assigns a value tovarwhen the condition is not true:int var; if (some condition) { var = 5; } else { var = 3; } System.out.println(var);
-
-
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
iforif-elseblocks. 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)istrue, 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
iforif-elseblocks. In the example above, changing theelse ifto anelsewould do the trick:public static int getVal(int valType) { if (valType == 1) { return 3; } else { return 5; } } -
In my TerrierShipping program, I have an
if-else ifstatement that I’m using to determine which value to use, but it always uses the value from theelseblock, 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 (theequalsmethod) to compare the strings. For an example of this, see the way that the starter code we provided inmainchecks for the case in which the user enters the string"Q". -
In my TerrierShipping program, I’ve written a method that returns a value. However, that value doesn’t seem to be available in the
mainmethod 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-whileloop in themainmethod.getItemType(console); // XXX: incorrect
Note that the method call to
getItemTypethrows 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 themainmethod.You should do something similar when you call a method that returns a value.
(By the way, it’s worth noting that although the
getItemTypemethod uses a variable calleditemTypeto store the string entered by the user, this is a completely separate variable from the variableitemTypein themainmethod. Therefore, we still need to have the method return the item type, and we need to use that return value in some way in themainmethod.) -
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 += numwill increment the value ofvalby the value ofnum.On the other hand,
val =+ num(with the = coming before the +) will simply assign the value ofnumtoval. -
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:
- 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.
- 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.