The goal today is to actually write your first Java programs, then compile and run them. In particular, you will practice some basic operations on Strings, in addition to continuing to practice some of the algorithmic thinking we had previously been doing.
Starting this week, you will be doing labs in pairs, using special lab accounts. So you’ll need to find a partner for this week (or possibly a third, if the number of students in lab today is odd). You will see a little window near the upper right of the screen. Each of you should type your username in the box and hit ’+’ so that you are listed in “Current users.”
At the end of lab, you can copy your work to your own account; there are instructions at the end of this write-up about how you can do that.
You can find an online version of this writeup from the class page. You will want to pull that up because the online version contains some links that you way wish to follow.
You may find the handouts from recent class meetings helpful. (If you don’t have it with you, you can look at them with a command like
I have also provided a page of Java notes with additional information—which you can reach from the online version of the lab. (If you right-click on the link, you’ll have a chance to open the page in another tab or window.)
Skim the entire lab before you start; then read each section in its entirety before you start working on it. Think about what you do, because you’ll need to be able to do it again in the future.
Make a new directory for this lab and cd into it.
I am providing starting files for the programs you are going to write. Copy them from the course public directory. (Don’t miss the dot as the second argument.)
Look at the list of files now in your directory.
You should see Greeting.java, Palindrome.java, and StringToInt.java.
This first exercise is just to step you through the process of writing, compiling, and running a Java program. Open Greeting.java in Emacs.
Remember that the ampersand means that the terminal window will still be active even though Emacs is running.
Find the line that has @author; replace the names there with yours. Every program you write will have one of these tags to identify who wrote it. Now replace the comment that says “your work goes here” with a statement that will print a greeting to the screen.
Compile your program:
If the compiler complains, then look carefully at your program (you probably wrote only one line, so it should be easy to find the problem) and see if you can figure out what’s wrong and try again. If the compiler does not give you any errors, then congratulations, you have compiled your first program. Look at the contents of the directory again.
You should see Greeting.class in addition to the files that were there before.1 If you want to list only the source files, you can type
This means, ”list everything with a name that ends with ’.java’.”
Now run the program.
Note that when you compile, you compile a file, so you need to give javac the name of the file, Greeting.java. When you run, you run a program, and the name of the program is Greeting, not Greeting.class. The Java virtual machine knows to look for a file called Greeting.class for the compiled version of the program Greeting.)
Now that your program runs correctly, give your partner a HIGH FIVE!
Now it is time to do some more sophisticated things with values of type String. A string value consists of a sequence of characters, which makes it a little bit like the arrays that we used in pseudocode. If you have a String variable named s, the expression s.length() will yield the number of characters that it contains. You can get the single character at position i with the expression s.charAt(i). (Remember that we always start counting with zero.)
Each of these expressions is said to call a method on s, which is how we do operations on String values. The standard way to describe methods looks something like this:
This tells us the names of the methods, with the type of the result before it (int for length()), and what additional values we need to provide to them in the parentheses following (none for length(), a single int value for charAt()). We call the things inside the parentheses the method’s parameters. When we write a call to one of these methods, we start by naming the string we want to do it on, which we call the receiver for the call.
One way that Strings are different from pseudocode arrays is that a string value is immutable: we can get the character at any position, but we can’t change it.
These two methods should be all that you need to use for this lab.
As part of the pre-lab, you should have written pseudocode to convert an array of (integer) digits into the value that they represent. You are now going to do something similar with a String.
Open StringToInt.java (you can do this in the same Emacs session by clicking on the “open” button, or by typing ^X^F and filling in the filename). Your task here is to take a String that the user inputs and convert it into an int.
Before you get started, fill in the heading at the top of the file, listing yourselves as the authors and fixing anything else needed there.
The part that prompts the user for a string has already been written—it requires some stuff we have not yet talked about; so don’t let it intimidate you. Just know that by the time that stuff is done, the variable str will contain a String that the user of the program has typed in. Assume the string contains only digits, such as ”142364”.
Your task is to store the equivalent integer value in the int variable x. Think about what you know how to do (Can you pull one character out of a string?) and what you need to do (How do you combine the values of the digits in a numeral?). Here is one bit of magic that you’ll need: the Java way to convert a single digit from a character to an integer. If you have a char value—let’s say, the variable c—that contains a decimal digit, then you can turn that digit into the equivalent int—say, to store in the variable i—by
(The 10 is there to indicate that the digit is in decimal—base 10. Sometimes programmers want to use a different base.)
Do not change any of the lines of code I have given you; write what you need in between the comments that tell you where to put it.
You may assume the the string you are given contains only digits, and you don’t need to worry about the number being too large to fit in an int. Your program does not need to work correctly for incorrect input. (That’s only because this is your first crack at programming; in principle, programs should deal with incorrect input gracefully.)
Do not change any of the lines of code I have given you (except you may delete the ”add your code here” line). But make sure you do add your names after the @author tag.
When you compile, you will almost certainly get errors. Don’t be afraid to ask for help. When it compiles without errors, test the program by running it on several inputs. Do not be surprised if it doesn’t work right; go back and fix it.
Tip: Compiler messages contain the number of the line where the error was discovered; it is possible that the actual mistake in the program occurs earlier. Emacs is set to tell you what line your are on (prefixed with L in the status line below your file), and it has a command to jump to a specific line number; see the Emacs tips page for more information.
When your program is working, go on to the next problem.
A word, phrase, or sentence is a palindrome if it is the same backwards and forwards. Some interesting palindromes, if we ignore capitalization, punctuation, and spaces, are
We’ll keep things simpler today, assuming that our input consists of only lowercase letters. So some of the above would have to be provided to our program as
Open the file Palindrome.java. Before you do anything else, fill in the heading at the top of the file, adding yourselves to the authors and fixing anything else needed there.
Your task in this problem is to make the program test whether a single word entered by the user (stored in the variable str) is a palindrome. The part of the program that prompts the user for a string has already been written—it requires some stuff we haven’t talked about; so don’t let it intimidate you.
Some English words that are palindromes are level, toot, racecar, and wow. Print an appropriate message to the screen.
Think about how this problem resembles part of your pre-lab assignment, using a String instead of an array. So work out how you could use the method you came up with to solve this problem.
As before, compile and test.
First, make sure that you have properly added your names to all of the files that you will be turning in.
As a general rule, you will be asked to turn in your labs by using a command that bundles up your files and puts them in a grading directory. Sometimes we will ask you to turn in a printed copy of certain files. Today, you’ll do both.
The first thing you need to do is prepare a typescript file that records you compiling and running your files. Here are the steps to take:
Everything that goes to your terminal will now also be recorded in the a file named typescript.
This program is so simple that a single run will do.
To turn all of this in electronically, use this command:
Be sure that you see the report of successful submission.
Now print all of this out in a reasonably neat manner, using the command
The command a2ps formats the output nicely, two-up (with two pages per side) and sends it to the lab printer. The --file-align=virtual tells a2ps to not start each new file on a new sheet.
If you look at the way your typescript prints, you may see some gibberish in addition to what you expect. The typescript recording isn’t clever enough to deal with any command-line editing that you do in the terminal; we’ll cope with that.
Turn in the hard copy to me.
When you come back later, you may not be working on the same lab account. So you will probably want to copy what you have done today to your own account. You can do that using the file browser without too much difficulty.
In the instructions that follow, the username is mortimer.snerd; substitute yours.
All that effort gets you another browser window, but this one is for your home directory.
When you are done, disconnect your home directory. Your partner will want to do the same thing to copy the files to his/her home, too.
Please log out when you are done.
1There may one or more additional files with names that include Greeting.java; Emacs makes those in order to be a little bit safer. You may ignore them for now.