Lab 1: Getting started, Java basics
Task 0: Review lab policies
-
Labs consist of exercises that are designed to reinforce the material covered in lecture and to prepare you for the problem sets.
-
Every lab section has two staff members: a teaching assistant (TA) and an undergrad course assistant (CA). They and the entire course staff are looking forward to working with you in labs and office hours.
-
Attendance:
-
It is important that you attend the lab for which you are registered on StudentLink. If you need to attend another lab section on any given week, please notify your instructor in advance.
-
We don’t grade the lab exercises. However, starting with next week’s lab, your attendance at lab will count towards your participation grade. If you attend 85% of the lab sessions over the course of the semester, you will get full credit for lab participation. See the syllabus for more details.
-
For each lab, you must be checked off by either a teaching assistant or course assistant in order to receive credit for the lab.
-
-
Participation:
-
To get full credit for participation in lab, you must work productively for the entire lab session. You will not be penalized if you cannot finish all of the lab exercises, but we strongly encourage you to complete the exercises outside of lab, and check your answers with the solutions when posted.
-
Don’t hesitate to ask for help! The course staff is more than happy to help you with any questions that you may have, and we will be coming around to assist you during lab.
-
Note
You cannot get credit for completing the lab tasks at home and coming to lab only to sign the attendance sheet. Part of participation is attending the lab to interact and ask questions.
-
Collaboration.
- You are encouraged to work with your classmates on the lab exercises as directed by your lab TA.
Task 1: Simple debugging
Using folders
You should create a separate folder for each lab.
If you haven’t already created a folder named cs112
for your
work in this course, follow these
instructions to do so.
Then create a subfolder called lab1
within your cs112
folder
for your work on this lab, and put all of the files for
Lab 1 in that folder.
In Lab 0, you should have installed VS Code on your computer. Let’s start with a simple exercise to get used to the VSC development environment.
-
Download the following file: Debugging.java
Make sure to put the file in the
lab1
folder that you created above. If your browser doesn’t allow you to specify where the file should be saved, try right-clicking on the link above and choosing Save as... or Save link as..., which should produce a dialog box that allows you to choose the correct folder for the file. -
In VS Code, select the File->Open Folder or File->Open menu option, and use the resulting dialog box to find and open your
lab1
folder. (Note: You must open the folder; it is not sufficient to simply open the file.)The name of the folder should appear in the Explorer pane on the left-hand side of the VS Code window, along with the name of the
Debugging.java
file that you downloaded above. -
Click on the name
Debugging.java
, which will open an editor window for that file. -
Now pretend you are the Java compiler and try finding all the bugs in the program. How many errors can you find?
You can try to run the program by using the F5 key, or by right-clicking the name of the program in the Explorer pane and choosing
Run
orRun Java
. -
If you fixed all of the syntax errors, your program should run. If it doesn’t, look through the compiler error messages and see if you can fix the remaining issues. Make all of the fixes
-
Now look at the result. Is it correct? If not, there may be a logic error. Can you find it?
Task 2: Writing our first custom program
In this task you will write a simple program that involves user input and conditional execution.
Getting started
-
As needed, open your
lab1
folder using the File->Open Folder or File->Open menu option in VS Code. -
Select File->New File, which will open up an empty editor window.
-
Select File->Save, and give the new file the name
Greeting.java
.
Writing the program
-
Add comments at the top of the new file that include:
- a brief description of what the program is supposed to do.
- your name and email address
See the comments that we provided in the starter code for previous task for an example of what they should look like.
-
Below the comments – and before any class header – add an
import
statement for thejava.util
package:import java.util.*;
Including this
import
statement will allow you to create aScanner
object in your program. -
Create a class named
Greeting
that will serve as a container for your program. -
Inside the
Greeting
class, add amain
method with the usual header. -
Start the
main
method by creating aScanner
object for getting user inputs from the keyboard and assigning it to an appropriate variable. -
Now add code to the
main
method of your program so that it:- issues a prompt asking for the user’s first name
- reads the name from the keyboard
- displays a polite (or not so polite!) greeting message
- prompts the user to enter their age.
Use the methods of the
Scanner
class to perform the user input. You should use the methodnext
to read and return a string value andnextInt
to read and return an integer value. Here’s an example of what a run of the program should look like:Please enter your first name: Gloria Hello Gloria, Welcome to CS112!!! How old are you Gloria? 57
-
Enhance your program to output a personal insult based on the value of
age
that was entered. Use the following age-range descriptions when creating your insults:age range description ----------------------------- 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 are speechless!!
A few possible sample runs (but feel free to be creative!):
Please enter your first name: Aileen Hello Aileen, Welcome to CS112!!! How old are you Aileen? 21 Wow Aileen! You just made it! Please enter your name: Mike Hello Mike, Welcome to CS112!!! How old are you Mike? 19 Wow Mike! You have 2 more years to go!! Please enter your name: John Hello John, Welcome to CS112!!! How old are you John? 13 Wow John! You are such a dweeb!!
Task 3: Debugging a static method
Let’s continue to practice our debugging skills using VS Code. This time we will focus on debugging a simple static method.
-
Download the following file: Debugging2.java
Make sure to put the file in the
lab1
folder that you created above. If your browser doesn’t allow you to specify where the file should be saved, try right-clicking on the link above and choosing Save as... or Save link as..., which should produce a dialog box that allows you to choose the correct folder for the file. -
If your
lab1
folder isn’t already open, use File->Open Folder or File->Open to find and open it. -
Click on the name
Debugging2.java
in the Explorer Pane on the left-hand side of VS Code, which will open an editor window for that file.You should see a simple static method called
triArea
, and amain
method that includes an example test call to that method. -
Fix all of the syntax errors in
triArea
that prevent the program from compiling and running. Once everything works, you should see the following:Testing the triArea method triArea(10, 3) is 15.0
-
Once the code compiles and runs, you should test the method for any logic errors.
The provided test produces the correct result, since the area of a triangle with base 10 and height 3 is indeed 15.0.
However, one test is almost never good enough! Try adding this line to your
main
method and rerunning the program:System.out.println("triArea(9, 3) is: " + triArea(9, 3));
You should see a result of 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.
-
-
Rerun your program to ensure it works.
Task 4: Practice with Java methods
-
Download the following file: Methods.java
Make sure to put the file in the
lab1
folder that you created above. If your browser doesn’t allow you to specify where the file should be saved, try right-clicking on the link above and choosing Save as... or Save link as..., which should produce a dialog box that allows you to choose the correct folder for the file. -
If your
lab1
folder isn’t already open, use File->Open Folder or File->Open to find and open it. -
Click on the name
Methods.java
in the Explorer Pane on the left-hand side of VS Code, which will open an editor window for that file. -
You should see a sample method called
print3Times
that takes a string as its parameter and prints it three times. For example:print3Times("hello");
should output:
hello hello hello
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. -
Add a
main
method to the program, and add a test call tomain
forprint3Times
. Then run the program to see if produces the correct result. -
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
-
Add one of more test calls to
main
for your new method, and run the program to ensure that it works.
Extra practice
In Task 2 of this lab 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.
-
As needed, open your
lab1
folder using the File->Open Folder or File->Open menu option in VS Code. -
Select File->New File, which will open up an empty editor window.
-
Select File->Save, and give the new file the name
Greeting2.java
. -
Add an import statement and class header as you did in Task 2.
-
Write a static method named
greetMe
that takes no parameters and that performs the greeting portion of the original program: asking for and reading the user’s name, greeting the user, and asking for and reading the user’s age using methods of theScanner
class. You should be able to copy some of your code from Task 2 into thegreetMe
method.As this method does not return anything, what should its return type be?
-
Now create a
main
method that callsgreetMe
, and test the method by running the program. -
Write a static method named
insult
that takes two parameters: aString
which represents a person’s name and an integer which represents the person’s age. This method should create and return a String that is a personal insult based on the value of the argumentage
that was passed. Use the same insults that you used above in Task 2. -
Write test calls in the
main
method to test the methodinsult
by invoking it using literal arguments. For example:System.out.println(insult("OldMan Jack", 87)); System.out.println(insult("Jelly Bean", 5)); System.out.println(insult("Teen Tween", 15));
-
Call the method
insult
from within the methodgreetMe
. The call should pass in the expected arguments (i.e., the data that was input by the user), andgreetMe
should take theString
returned byinsult
and display it. -
Once
insult
is being called correctly from insidegreetMe
, you can remove your earlier test calls toinsult
from insidemain
. -
If you do all of the above correctly, the program should now execute as it did in Task 2:
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: Gloria Hello Gloria Welcome to CS112!!! Gloria how old are you? 57 Yikes!!!
-
Test out your program by entering a negative age. What does your program do? What should it do? Revise the program to handle the possibility of incorrect input?
-
Test out your program by entering an age of 20. Is the resulting message grammatically correct? Fix it as needed.
-
Look at the code you have written. Do you see any repeating code segments? If so, how could your code be logically restructured?
-
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? —>
More 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.