Outline

Learning Goals

  • Programming:
    • Unix basics
    • Input and output
    • Mathematical expressions
  • Methods:
    • The quadratic formula

Overview of Unix

The ibooks you've been using run a version of Unix called MacOS X. We're going to use the terminal program, which lets us move around the computer's files and type commands to the operating system. In order to do this, you need to learn a few Unix commands.

Type pwd. This stands for "print working directory," and it tells you the directory you are in. You should see something like /Users/student. This is your "home directory."

Type ls. This is short for "list," and it shows you a list of all the files and directories in the current directory.

One of the directories in your home directory is Documents. To move into that directory, type cd Documents. cd is stands for "change directory." Now, if you type pwd again, you will see that you are in a different directory.

Many Unix commands consist of two parts: the command name and a file name. cd is one such command. We will be using commands like this a lot, so let's try out one more. Type ls again. One of the files should be pretzel. Type cat pretzel. This tells Unix to run a program called cat on the file pretzel.

Now type cd with no directory name. This will take you back to your home directory. If you ever get lost in the directory structure, you can type cd (with no directory name) and you will go "home."

Type cat pretzel again. You should get an error message. The command doesn't work because pretzel isn't in the current directory (your home directory).

Intro to Java programming, "Hello World!"

Here is your first Java program. Let's have a look at it.
/* 
   The main unit in Java is the "class."  
   A class is a set of variables and
   functions (also called "methods").  
   All programs in Java are contained in 
   one or more classes.
 */
public class HelloWorld {

    // The main method is where the program starts.
    public static void main(String[] args) {

        // This method prints text to the screen
        IO.print("Hello World!\n");

    }

}

The first line of code gives the program its name. The name of the file before the .java part must be exactly the same as the name of program. Our program is named HelloWorld, therefore it must be saved in a file named HelloWorld.java.

The next line, public static void main(String[] args), defines a method which is where the program begins. Later, you will write programs that define more than one method. However, you must always define main() and it will always be the first method that executes (regardless of whether or not it is the first one you define).

The line IO.print("Hello World!\n") does the only work in the program; it prints "Hello World!" to the screen. This statement refers to a method, print(), contained in the class IO. IO is not a standard Java class; it is something we have provided for you to simplify Input/Output (I/O).

Notice that the body of the class is enclosed in curly braces and the body of the main() method is also enclosed in curly braces. Also, each block of code is indented.

Also notice the comments in the file. Comments are text in the source code that the computer ignores; they are there only for humans to see. Java has two ways of specifying comments. Multi-line comments (such as the first comment above) begin with /* and end with */. These comments can go over as many lines as you want. Single line comments begin with // and extend to the end of the line.

Now that we've seen what's in the file and how it works, save the file to your computer in the Documents directory. To run the program, we must first compile it. Compiling turns the program into code the computer can understand. To compile the program, type:

    % javac HelloWorld.java
    
(this is one of those Unix commands that operate on a file). Now you should have a new file, HelloWorld.class. This is the compiled file. To run it, type
    % java HelloWorld
    
You should see a greeting.

This is a pretty simple program. All we have done is to print a simple message to the screen. Notice that we follow the print command with text in quotes. We refer to text like this as a string, since in the computer it is stored as a string of characters. The last character in the string is a little unusual. It is a special character, and we know it is a special character because it is preceded by a backslash '\'. Backslash-n ('\n') is the newline character. It tells the computer to go to the next line. Try running the program without it and see what happens.

The line ends with a semicolon. Semicolons in many programming languages tell the computer that the current command is finished. This becomes important when commands get so complicated that they stretch over many lines.

Now I'm going to show you how to make the program more interesting by having it ask the user for his or her name and then greet the user by name.

Of course, when we're doing scientific programs we're more interested in reading in numbers than text. There are two types of variables for numbers. They are called "int" and "double." (Note that they start with lowercase letters, not uppercase like String. This is important.) int variables hold integers, and double variables hold floating point numbers. You use IO.inputString() to read in a String; not surprisingly, you use IO.inputDouble() to read in a double and IO.inputInt() to read in an int.

Below is a mostly completed program that calculates the user's Body Mass Index (BMI). The BMI is a number that tells you whether or not you are fat. The parts missing from the program are the variable types and input statements. Try running the program where height, weight, and bmi are all ints, and where they are all doubles. Do you get different answers? Which answer is correct? What is different about the two ways of doing it?

public class BMI {
    public static void main(String[] args) {
        ???? height, weight, bmi;

        IO.print("What is your height in inches? ");
        height = IO.???();
        IO.print("What is your weight in pounds? ");
        weight = IO.???();

        bmi = weight / Math.pow(height,2) * 703.0;
        IO.print("Your body mass index is " + bmi + "\n");
    }
}

Numerical error

There are a number of properties of numbers that you are probably all familiar with from algebra:

Do these properties hold in computer math? Not always. Let's look at this Excel spreadsheet of stupid number tricks.

Obviously Excel has problems, but what about Java? Do all types of computer math have these failures? Let's find out. Write a Java program that does the same calculations as the spreadsheet and prints out the answers. Are the answers correct?

Here's another thing to try: You've seen examples where the commutative, associative, and distributive properties fail. Can you find an example where the multiplicative identity property fails? That is, can you find a number x so that 1/x * x is not equal to 1?

These are miniscule errors, though. Do they really matter? Yes, they do, particularly when many such errors occur and are compounded. Here are a few examples of problems that were caused by small errors in computer math.

Why do these rounding errors occur? Consider the number of numbers -- it is infinite. Computers can't represent every possible number, because that would require an infinite amount of memory. Instead, they choose a subset of all possible numbers. This is still quite a few, but it is not all. If the result of a computation -- say a number x -- falls between two of the numbers a computer can represent, it picks one of the representable number and "pretends" x is equal to that number.

Arithmetic Operators

You've already seen several arithmetic operators in Java (+, -, *). Here is a more comprehensive list:
+ Addition
- Subtraction, take the opposite of
* Multiplication
/ Division
% Modulus Division
Math.pow(a, b) Exponentiation (ab)
Note that there isn't an operator for exponentiation; you have to use a function.

Besides those, you can also use parentheses in mathematical expressions. Java follows the normal algebraic order of operations: first everything in parentheses is evaluated; then exponentiation is done from left to right; then multiplication, division, and modulus division from left to right; then addition and subtraction. (This is also known as PEMDAS for "Parentheses, Exponentiation, Multiplication, Division, Addition, Subtraction" or "Please excuse my dear Aunt Sally.")

Here are some examples of mathematical expressions in Java:

1. io.print("145 squared is " + Math.pow(145, 2) + "\n");
2. volume = length * width * height;
3. fOfX = 3*Math.pow(x, 2) + 2*x + 14;
4. speed = distance / (endTime - startTime);
5. opposite = -x;

Note that the result of a mathematical expression can be used right away, as in the print statement, or it can be assigned to a variable for use later.

Exercise: The quadratic formula

Some of you may already know what a quadratic equation is. It is an equation which has a variable raised to the second power. Here is an example of one:

One important application of quadratic equations is to find the height of an object that is falling. Here is the simple form of the equation for that:

Do you see how the variables in the height equation line up with the variables in the general quadratic equation?

You may also have memorized the solution to these types of equations. The solution is a well-known formula called the quadratic formula:

Below is a program that solves quadratic equations using the quadratic formula. Unfortunately, it has several errors. See if you can find and correct the errors.

public class quad {
    public static void main(String[] args) {
        int a;
        int b;
        int c;
        int x1, x2;

        IO.print("This program solves quadratic equations");
        IO.print("by using the quadratic formula.");
        IO.print("What is a? ");
        IO.print("What is b? ");
        IO.print("What is c? ");
        a = IO.inputInt();
        b = IO.inputInt();
        c = IO.inputInt();

        x1 = -b + Math.sqrt(b^2)-4ac / 2*a;

        x2 = -b - Math.sqrt(Math.pow(b,2) - 4ac / 2a;

        IO.print("x = " + x1 + " or " + x2 + ".");
    }
}

To see if your program is correct, try it on these inputs:
abc
141
.5101.5
-.5 * 9.80500
01010
10110

Your program should be able to do the first several with no trouble, but it will give you an error on the last two rows unless you make your program more complicated.

StarLogo

Starlogo is a computer modeling program which allows groups of turtles to interact with each other and the ground (called the "patch"). The turtles are able to move, aquire information about other turtles near them, about the ground around them, change their color and the color of the patch.

The commands are entered in 2 places. First the turtle command center. These commands generally deal with turtle movement and interaction with the patch. The second area is the oberver command center. The observer commands are generally used to set up the screen by creating turtles, asking them to create certain color patterns in the patch, and destroying any extra turtles.

The commands in both centers can be grouped in procedures. A sample procdure could tell a turtle to check the patch color, and if it is yellow, take 20 steps forward and make another yellow spot. After procedures are formed, the user can create buttons to run them.

1) Practice moving a single turtle
* Create 1 turtle
* Practice the "fd" command
* Use "lt" and "rt" commands to turn the turtle
* Use "random" commands to move multiple spaces
* Use "stamp" command to manipulate the patch color

2) Practice Procedures
* Teach turtles to walk in a circle and mark their path with the repeat function. Also use loop buttons to repeat procedures.
* Randomly set patch patterns with heading and jump commands (i.e. grass or woodchips).

3) Logic Statements
* If-then-else statements (circle). Teach the circle walking turtle from above to stop when it completes one circle.

4) Collectively design a System (Woodchips and Termites)
a. Use previously designed system to set up random yellow scatter of woodchips.
b. Create a set of turtles or "termites"
c. Teach the termites to move
d. Teach the termites to pick up chips
e. Teach the termites to find piles
f. Teach the termites to put the chips down.