Old version
This is the CS 112 site as it appeared on December 31, 2020.
Lab 3: Static methods and strings in Java
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 lab3
for your work on this lab, and put all of the files for this lab
in that folder.
Piazza Pointers
-
You can — and should! — search for related questions before you post a new question.
-
You can post anonymously, so that other students won’t see your name.
-
If you need to show us part of your work in order to ask your question, you can make a private post that only the course staff can see.
However, if your question that doesn’t reveal your work, please don’t post it privately, because then other students can’t benefit from it. Non-private questions are also more likely to get a quick reply, because more people can see and answer them.
Task 1: Simple Debugging (and static methods)
Let’s start with a simple exercise to continue practicing with the Development environment. Download the following file on your computer and try finding all the intentional bugs in the program.
In order to add the Debugging class to our project we can simply
copy and paste the contents of Debugging.java
file into your IDE.
Now you can work with Debugging.java
and fix the errors you see.
-
Once our code compiles, we should test our methods. We have two ways we can do so.
-
We can add a main method to our
Debugging.java
file and include calls to test our method. Example:System.out.println(triArea(10, 3));
should output:
15.0
-
We can write a separate simple test class containing a main method that includes calls to test our method.
System.out.println(Debugging.triArea(10, 3));
should also output:
15.0
Note the difference! Because this call is now being made in a method which is written in a separate class to which the method
triArea
belongs, we need to prepend the class name when we call the method.
In both cases, this result is correct, because the area of a triangle with base 10 and height 3 is indeed 15.0.
-
-
One test is almost never good enough! Try adding this line to (one of) your main functions and rerunning. What is the result? Is it correct?
System.out.println(Debugging.triArea(9, 3));
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.
-
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 computeb/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.
-
-
Save your code and rerun your program to ensure it works out
Task 2: Practice with Java methods
Task 2.1: Writing static methods
This task asks you to write a series of static methods.
Begin by downloading this file: Methods.java
.
Open (copy and paste) it in your IDE, and add your methods to the
class that we have given you in that file.
You should also add a main method to test out each of the methods you write. We show the sample calls below as though they are being made from within the main method of this program.
-
A static method called
print3Times
that takes a string as its parameter and prints it three times. For example:print3Times("hello");
should output:
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. -
Write a static method called
printNTimes
that takes an integern
and a string (in that order) as its parameters and prints the stringn
times. For example:printNTimes(5, "hello");
should output:
hello hello hello hello hello
and,
printNTimes(2, "hello");
should output:
hello hello
-
In Task 2 of Lab 2 you were asked you to write a program that prompted for your name and age as input and displayed a funny message based on your age. We are going to do something similar, except we are going to decompose our program into two logical methods.
Write a static method called
greetMe
that greets you. The method should issue a prompt asking for your name, display a polite (or not so polite) greeting message and then prompt you to enter your age.Use the methods of the Scanner class to perform the user input. You should use the method
next
to input a string value andnextInt
to input an integer value. This method may run as follows:Please enter your name: Christine Hello Christine Welcome to CS112!!! Christine how old are you? 57
As this method does not return anything, what
type
of method should it be? -
Test out your method by following the examples below. What does your program do in each of the two cases? What does your program do if you used the method
nextLine
instead ofnext
to input the name? Make sure you understand why.Please enter your name: Christine Papadakis Please enter your name: Christine 57
-
Write a static method called
insult
that has two paramaters, a String which represents a person’s name and an integer which represents the persons age. This
method should create and return a String which is a personal insult based on the value of the argumentage
that was passed. Use the following age cuttoffs (or variations of your choosing) for creating your insults:1 <= 10 everyone is sweet 11 <= 17 they are dweebs 18 <= 20 they are counting down to legal age 21 exactly they just made legal age 22 <= 29 they are counting down to 30 30 <= 40 they are suffering adults 41 < 50 they are miserable adults >= 50 you a speechless!!
Test your method by calling it with literal arguments. Example:
insult( "Jack Ma", 87 ); insult( "Jelly Bean", 5 ); insult( "Teen Tween", 15 );
-
Call the method
insult
from within the methodgreetMe
passing it the expected arguments (i.e. the data that was input). Executing the methodgreetMe
now may run as follows:Please enter your name: Jacob Hello Jacob Welcome to CS112!!! Jacob how old are you? 12 Holy cow Jacob, you are such a dweeb!!! Please enter your name: Sarah Hello Sarah Welcome to CS112!!! Sarah how old are you? 21 Holy cow Sarah, you just made it!! Please enter your name: Mike Hello Mike Welcome to CS112!!! Mike how old are you? 19 Holy cow Mike, you have two more years to go!!! Please enter your name: Chris Hello Chris Welcome to CS112!!! Chris how old are you? 57 Yikes!!!
-
What did you have to do within the method
greetMe
to ensure that the insult message is displayed? -
Test out your program by entering a negative age. What does your program do? What should it do? Did you consider the possibility of incorrect input?
-
Test out your program by entering an age of 20. Is the resulting message grammatically correct?
-
Look at the code you have written. Do you see any repeating code segments? If so, how can your code be logically restructured?
-
Create a new Java program class and write a main method in this class that calls the static methods you have just written. What do you have to do differently to call these methods? Make sure you understand why.
Challenge
- How could you enhance your method
greetMe
to continually prompt for aname
andage
? What loop structure might you use and how can you determine when to stop the loop?
Task 3.0: Java Strings (as needed)
Task 3.1: String objects and their methods
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 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) |
|
|
concatenation |
|
|
finding the number of characters |
|
|
indexing |
|
|
slicing |
|
|
converting all letters to uppercase |
|
|
converting all letters to lowercase |
|
|
determining if a substring is in a string |
|
|
finding the index of the first occurence of a character or substring |
|
|
testing if two strings are equivalent |
|
|
Additional notes:
-
Java has a separate type called
char
for values that consist of a single character. Literals of this type are surrounded by single quotes (e.g., the'o'
in the calls1.indexOf('o'))
, whereas string literals must be surrounded by double quotes. (In Python, there is no separatechar
type, and string literals can be surrounded by either single or double quotes.) -
The
charAt()
method that we use for indexing in Java returns a value of typechar
. For example, the calls1.charAt(0)
in the table above would return thechar
value'B'
, since'B'
is the first character in the string"Boston"
.
Task 3.2: Strings and their methods
Given the information above, here are the tasks you should perform:
-
To ensure that you understand how the above string operations work in Java, write a simple Java test program which you can use to play around with the different string operations.
-
Begin by initializing two string variables in your main method (which can be used in the later tasks). Example:
String s1 = "Boston"; String s2 = "University";
Test that these variables still have their values
System.out.println(s1);
should output:
Boston
and,
System.out.println(s2);
should output:
University
If for some reason the variables don’t have these values, redeclare the variables
-
We’re now going to solve a series of puzzles in which we construct an expression involving operations on
s1
and/ors2
to produce a specified target value.For example, let’s say that we want to construct an expression involving
s1
ors2
that produces the following value:"ton"
One possible expression that works for this puzzle is
s1.substring(3, 6)
.System.out.println( s1.substring(3, 6) );
-
Now solve the puzzles below by writing in your main function for each problem in your
StringTest.java
file.-
Construct an expression involving
s1
ors2
that produces the following value:"Uni"
-
Construct an expression involving
s1
ors2
that produces the following value:"UNI"
Hint: Chain two method calls together. For example:
System.out.println( s1.toLowerCase().substring(0, 3) );
should output:
bos
-
Construct an expression involving
s1
ors2
that produces the following value:'v'
Note that the single quotes mean that you must produce a
char
, not aString
. See the notes under the table above that discuss thechar
type. -
Construct an expression involving
s1
ors2
that produces the following value:"STONE"
-
-
Write a static method called
replaceStart
that takes two stringss1
ands2
, and does the following:-
If the length of
s1
(call its1Len
) is less than the length ofs2
, the method returns a string in which the firsts1Len
characters ofs2
are replaced bys1
. For example:System.out.println( replaceStart("abc", "xxxxxxx") );
should output:
abcxxxx
and,
System.out.println( replaceStart("hello", "xxxxxxx") );
should output:
helloxx
-
If the length of
s1
is greater than or equal to the length ofs2
, the method just returnss1
.System.out.println( replaceStart("hello", "bye") );
should output:
hello
-
-
Why does the method
replaceStart
need to be called from within theprintln
method? In other words, what would you expect to happen if our program just made the call toreplaceStart
on its own line, rather than calling it as part of aprintln
? Make sure you understand.
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.
-
Go to Practice-It.
-
Create an account.
-
Select the group of problems entitled Building Java Programs, 3rd edition.
-
Select BJP3 Chapter 3: Parameters and Objects.
-
Try any of the following:
- BJP3 Self-Check 3.18-3.21
- BJP3 Exercise 3.17–3.22
The system will test your solution and tell you whether it is correct.