Lab 2: First Java programs

The goal 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). There are instructions at the end of the lab about how you can copy your work to your own account.

For this lab, I have provided another page of Java notes that you may find helpful. (If you right-click on the link, you'll have a chance to open the page in another tab or window.)

1. Set up

Make a new directory for this lab and cd into it.

$ mkdir lab2
$ cd lab2

I am providing stubs for the programs you are going to write. Copy them from the course public directory. (Don't miss the dot as the second argument.)

$ cp /cslab/class/csci235/lab2/* .

Look at the list of files now in your directory.

$ ls

You should see Greeting.java, StringToInt.java, and Palindrome.java.

2. Printing a greeting

This first exercise is just to step you through the process of writing, compiling, and running a Java program. Open Greeting.java in XEmacs.

$ xemacs Greeting.java &

Remember that the ampersand means that the terminal window will still be active even though XEmacs is running.

Add your names to the end of the line with the @author tag. Then add a line to the program (inside the main section) that displays a greeting to the screen. Then compile the program.

$ javac Greeting.java

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.

$ ls

You should see Greeting.class. If you want to see only the source files, you can type

$ ls *.java

This means, "list everything that ends with '.java'."

Now run the program.

$ java Greeting

(Remember 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!

3. Testing for palindromes

A word, phrase, or sentence is a palindrome if it is the same backwards and forwards. (For phrases and sentences, we ignore punctuation, spaces, and capitalization). Some interesting palindromes are

Open the file Palindrome.java. Your task in this problem is to test if a 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've barely touched on; so don't let it intimidate you.

For now, assume that the string the user provides is a single word, and that you don't need to worry about a mix of uppercase and lowercase. (If you have time, you can remove those restrictions in part 5.) (Some English words that are palindromes are level, toot, racecar, and wow). Print an appropriate message to the screen.

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 to 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, then 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. XEmacs can be set to tell you what line your are on, and it has a command to jump to a specific line number; see the XEmacs tips page for more information.

When your program is working, go on to the next problem.

4. Converting a String to an int

This one is going to be a little harder. Open StringToInt.java (you can do this in the same XEmacs 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, adding yourselves to 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've barely touched on; 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 value in the int variable x. Think about what you know how to da (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

i = Character.digit(c, 10);

Do not change any of the lines of code I have given you (except you may delete the "put your code here" line).

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.)

As before, compile and test.

5. Extra: better palindrome testing

If you have time, it would be nice to make a better palindrome program that will work on sentences with mixed case, spaces, and punctuation. We'll call that new-and-improved palindrome program Palindrome2; so start by making a copy of your working program from part 3:

cp Palindrome.java Palindrome2.java
Then edit the new file Palindrome2.java in XEmacs. You will need to change the identifier in the line
public class Palindrome {
to Palindrome2 to match the file name, and you should update the description of the program.

Before you start changing things, take a minute to think through how to solve the problem. A bit of advice: when programming, it is almost always a good idea to do one thing at a time. You already have some code that tests whether a string is a palindrome, and it might be tempting to insert code to deal with odd characters into the middle of that. But the one-thing-at-a-time guideline suggests that you might think about “cleaning up” the input string first, so that you don't have to make complicated changes to your test for palindrome-ness.

6. To turn in

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 script file that records you compiling and running your files. Here are the steps to take:

  1. First, remove the compiled (.class) versions of your files. This time, that will be
    rm Greeting.class StringToInt.class Palindrome.class
    
    (Add Palindrome2.class if you did the extra part.)
  2. Now, start recording by giving the command
    script
    
    Everything that goes to your terminal will now also be recorded in the a file named typescript.
  3. List the directory, with long details:
    ls -l
    
  4. Compile with
    javac Greeting.java
    
  5. Run the program with
    java Greeting
    
    This program is so simple that a single run will do.
  6. Repeat the previous two steps for the other programs, StringToInt.java and Palindrome.java (plus Palindrome2.java if you did that part). You should run each of these programs several times, using different inputs to show that it works for a representative set of cases.
  7. End the script with the command exit.
To turn all of this in electronically, use this command:
/cslab/class/csci235/bin/handin lab2 Greeting.java Palindrome.java StringToInt.java typescript
Be sure that you see the report of successful submission. Now print all of this out in a reasonably neat manner, using the command
a2ps --file-align=virtual Greeting.java StringToInt.java Palindrome.java typescript
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.

Turn in the hard copy to me.

7. Copying your work to your own account

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 msnerd; substitute yours.

  1. In the Places menu (in the top bar), select Home folder to open a window. Browse to the lab2 folder where you have been working.
  2. Again, in the Places menu, select Connect to server. In the dialog that pops up, All that effort gets you another browser window, but this one is for your home directory.
  3. Navigate in this new window to where you want to put the files. You may want to make a new folder for just this lab.
  4. Use the mouse to select the files you want in the first (local) window and copy them to your 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.


Updated by Cary Gray,
original by Thomas VanDrunen
Last modified: Sun Sep 4 16:34:57 CDT 2011