Computer Programming and Java

Introducing the concepts of programming using Java as a base language

First, I recommend you use DrJava for practicing because it is a simple program where you can write Java code, compile it and interact with it. So you might want to download and install it, and then open it so you can test out what we will discuss and play around on your own. If you are a visual learner, this can be of great help.

RECOMMENDED: Read through this tutorial a couple times. You may not understand everything the first time, but perhaps the second or third time, some things will *click*

So if you've never programmed before, the thought might intimidate you and you might have a lot of questions. What is programming? How does it work? Why should I know it? Well basically, the idea behind programming is algorithms. Algorithms are a step-by-step, problem-solving procedure that solves - and will always solve - a problem. That is, it is a systematic series of actions that leads to a solution every time.

What's complicated about learning programming is that you have to start thinking like a programmer and that means when you think about a problem, you have to think logically of how it can be solved. How do you solve the multiplication problem 3*4? If your answer is simply, "Well, I just do because it's easy," then you're wrong. How would a programmer answer the question? You can multiply 3 by 4 by starting with 4 and adding 4 two more times. We'll come back to this later.

Similarly, how might you simulate a game of monopoly played by one person? Each turn, you roll the dice - which could have a value of anywhere from 2 to 12 - and move a piece, and depending on where you land, buy a property, pay a tax, pick a card, etc. These are all the things you'd need to think about in order to design a monopoly simulator.

Think about what is called pseudo-code, which is a listing of all the steps - in English - of what needs to happen, but is not in the programming syntax.

So, for example, for one turn of Monopoly, we need to:

  1. Roll the dice (generate two random numbers, each from 1 to 6, and add them)
  2. Move your piece to a spot on the board (determined by the dice roll)
  3. Handle the space
    • Pick a card if it's Chance or Community Chest
      • Move to a new space if the card says to
      • Pay or collect some monetary value if the card says to
    • Pay the rent if you land on someone's property
    • Buy the property if it's unowned and you want it
    • Do nothing
    • Roll again (if doubles were rolled)

See how you need to think about everything in terms of steps to reach a solution? You will program this at each step along the way. You will have to have different "methods" to handle the spaces and you will have variables to remember the value of the dice roll and where you are on the board and how much money you have, etc.

It's complicated! But you should have a good idea of the idea of algorithms now.

Think about this: how might you simulate a game of poker?

 Part 1: Variables [back to top]

Let's introduce the concept of variables. What is a variable? A variable holds some kind of value (a number, a true/false value, a series of characters or letters, etc.) and is able to change. There are different types of variables too. For instance, a variable that holds a number value could be an int (integer) and a variable that holds a bunch of letters, like a sentence, is called a String.

Java ⇒ English:

  • Value: a piece of data
  • Type: a kind of data
  • Variable: a place to store a value
  • Object: a structured group of variables
  • Class: a kind of object
  • Instance Variable: a variable belonging to a class

...just to get you familiar with the basic structure of Java and really, programming in general.

With that, here are the basic variable types:

  • int: any integer, i.e. 1, 5, -2, 24 ...
  • String: any string of letters, i.e. "Hello", "This is a phrase"...
  • double: any fraction, i.e. 3.2, 5.57, 6.2342 ...
  • boolean: only two values: true or false

Each variable MUST have a type and once you declare a variable's type, it can only store values of that same type. So if you created a "counter" variable which is an integer, then you cannot set it equal to "3.2" or "Hello" since neither of those values are an integer.

A bit about formatting:
Variable names cannot start with a number. And capitalization matters! The variable name "mySpace" and "myspace" are two different variables!! It is common practice that if your variable name is two words, you capitalize the second word - i.e. mySpace.

With that said, let's work on a simple declaration. In the Interactions pane of DrJava, type:

int count = 3;

...and press enter. Now what is this?! Well hold up, let's analyze:
- int is the variable type (integer)
- count is the name of the variable that we've decided
- 3 is the value of the variable
- ; (semi-colon) is needed at the end of every line in programming
This declaration says we've created a variable called "count" that's of type "int" - which means it holds an integer - and we've given it the value 3. Once we've declared it as an "int," whenever we reference it again, we need only to use the variable name - that is, "count."

So we have this variable now. Let's say we want to double it. How do we do this? We simply add another line of code that says:

count = count + 3;
or
count = count*2;

This sets our variable "count" to what its current value was + 3 (or *2) which will consequently make "count" = 6 (or double its original value).

We can do similar functions like subtract (-) and divide (/) as well.

So now, if you want to see what your value of "count" is - just type count and press enter and you will see its value.

Now think about this: how would you create a variable to represent how much money you spent on a candy bar and how would you add on 6% sales tax?

 Part 2: Classes and Instance Variables [back to top]

Now, Java is object-oriented programming, which means that you build programs as a series of different objects that interact with each other. So for example, if you wanted to build a program that simulates an amusement park, you might have separate objects for "rides," "foodcarts," "game stations," etc. and each of these would have their own special functions and instance variables, but they can interact with each other.

Think about the pseudocode for a minute in order to understand better. Let's say we're building a simple adventure game program that consists of an Adventure Player and Rooms (and the player just moves from room to room).

So, we would create a class called "AdventurePlayer" and a class called "Room." What are some properties (instance variables) of our AdventurePlayer class? Instance variables are like properties of an object/class. For example, if you create a "ride" object, it might have certain properties like "rideTime" or "rideLength." Well, we want our character to have a name, maybe some number variable to keep track of how healthy he is, how much money he has, etc. BUT we also want some way of determining which ROOM he is currently in! Hmm, ok so let's look at our property list for AdventurePlayer:

  • name
  • current position
  • number health points
  • number of hit points

A Note About Privacy...

When you declare an instance variable in Java, you have to specify whether it is public or private, that is, can anyone who uses the program you're creating use it? Or can it only be used within the program? If that doesn't make sense, think about this: if the program user can access a variable, then he/she can change it anyway he/she wants! We don't always want that! We only want the user to do some pre-defined function that changes the variable a certain way.

All instance variables should be private because we do not want the program user to explicity change any of these properties on his/her own.

So these are the properties of the "AdventurePlayer" object. These would be instantiated - or created - at the beginning of the class as such:

public class AdventurePlayer {
   private String name;
   private int healthPoints;
   private int hitPoints;
}

But you understand the rest of the syntax. You see that the variable "name" is of type String because it is a bunch of letters and the other variables are integers because they are some number value. You see how to alter variables.

There's something called a CONSTRUCTOR that is always necessary for a class. It's basically just a function that initializes all the instance variables when we create a new object. This is where you can specify our AdventurePlayer's name and initalize his healthPoints to 0 or something. Here's our code so far:

public class AdventurePlayer {
   private String name;
   private int healthPoints;
   private int hitPoints;

   public AdventurePlayer(String name1) {
      name = name1;
      healthPoints = 0;
      hitPoints = 0;
   }
}

So here we have created a class called AdventurePlayer, which is going to represent a character in an adventure game. The character has a name, which is a String, and a few integer values: healthPoints, hitPoints, currentPosition.

All of these variables are null--or 0 if they are ints--UNTIL we define them in the constructor. Note that the parameter of our constructor is a String, and this allows us to name the character. That is the only property that we can define - in this particular example - when we create our new character - healthPoints and hitPoints are automatically set to 0 and currentPosition is set to 1.

To create a new instance of this object, you write:

Welcome to DrJava.
> AdventurePlayer tim = new AdventurePlayer("tim");

...and that creates a new AdventurePlayer object whose name is "tim." You could have specified whatever name you wanted in the parenthesis, but for this example, we have chosen "tim." You can make another instance too - perhaps THIS character's name is "bob" :

> AdventurePlayer bob = new AdventurePlayer("bob");

Constructors are very important. It is where you create your object and define all of its properties. You have to do this before you can do anything else. But don't get confused - you don't create your object in your code - you create it in your interactions WITH the code.

Static Variables

Sometimes you want variables that can be accessed outside the program without first instantiating the class object. This is usually the case if you create a class that really doesn't need any instance variables or properties, like say if you were creating a class that just had a bunch of methods that calculated physics equations. This "physics" class wouldn't really need any properties that the methods would alter - everything would be done locally within the method. See Part 3 for more about methods - you can have static methods too, which, like static variables, can be called without first creating an object.

In fact, Java has a variety of built-in programs, one of which is a "Math" class, which has static methods just like we're talking about now. You can use the Math class to calculate things like exponents and square roots. Typing Math.pow(2,5) will give you 2 to the 5th power, or 32. Because the Math class has static methods, you don't have to first create a Math "object" if you want to use one of the methods.

Suppose now you want this adventure player to have another instance variable of type "Room" - referencing another class you can make - to represent the current room he is in. You go up to the instance variables and add:

private Room currentRoom;

Note that this variable is of type "Room." You can have objects as instance variables too! They don't always have to be an integer or String - they can be another object! So our player will have an instance variable of type Room called "currentRoom" - or whatever you want - and it will reference another object which has its own instance variables like a description, which we can access through our player's Room property.

...and in your constructor, you use add another parameter to specify what room the player starts in and then initialize the room instance variable to that room.

public AdventurePlayer(String name1, Room room1) {
   currentRoom = room1;

Then suppose your Room class has a method called getDescription() that returns a description of the room. In our interactions, we have only created a new AdventurePlayer object - affectionately named "tim" who has some reference to the current room he is in. Suppose we have a method called getCurrentRoom() that returns a reference to the Room object he is in. And then supposed we have a method in the Room class called getDescription() that returns a description of the room (a String). Using the AdventurePlayer object, we can get the room description by writing:

> tim.getCurrentRoom().getDescription();

tim.getCurrentRoom() now equals the Room object. Now we can call a Room object method - like getDescription() and that will give us the room description.

Ok ok, this is very complicated, but it's just an introduction. You'll learn more about this much later and you'll get used to the idea.

 Part 3: Methods [back to top]

Let's talk about methods. Methods are functions that change the variables. Like there are different variable types, so there are different method types:
void: this is a "command" method. These methods are mostly used for situations where you want to change an instance variable. For example, if you have a variable to keep track of the count of something, then maybe you want a method that just increments it. All it will do is increase the variable by one. Then next time you use the variable, it will have this new value.
int, String, double, boolean: these are "query" methods, which means they can change an instance variable or some other variable AND they give you something back, which means they "return" a new variable whose value is whatever you just computed in the method. So maybe you want a variable to represent the product of two numbers, which you generated through a multiply method. Take a look at this method declaration:

public int multiply(int i,int j) {}

Woah, lots of stuff, right? Well, let's see. We know that "public" means that the program user and access it. The "int" means that this is a query method and we should expect to receive a variable back that's of type "int". Our method is called "multiply" - and you can probably guess what we want it to do.

Now what is the stuff in parenthesis? Those are called parameters or arguments. You can input variables to methods to change them or to use in order to calculate something else. Here we've put in two integer variables, i and j. Now, these are not necessarily the actual variables, these are just "place-holders." That is, we could use our variable "count" as a parameter even though it's not called "i" or "j." We can do this because it's of type "int" and that's what this method calls for.

It's a bit confusing, yes, but if you play around on your own a bit, you'll see things come together. Let's now define the multiply method. All we need is a couple statements. These have to go INSIDE THE CURLY {} BRACKETS!. Our statement is:

int result = i*j;
return result;

This defines a new variable of type "int" called "result" and sets it equal to the product of the two variables that you put into the method as parameters. Then, on the second line, it turns that variable to you (which means it returns a reference to it so perhaps you could use it in another method).

So here is the full method:

public int multiply(int i,int j) {
   int result = i*j;
   return result;
}

Now that this method is defined, when you interact with the program, you call this method by writing multiply(3,5), for example, and it will print out 3*5 or 15. AND because it generates a new variable and returns it, you can even set a new variable equal to the method, i.e. int i = multiply(3,5). This will create a new variable called "i" that has the value 15.

Want to play around on your own? Use this code in DrJava and compile:

public class TestJava {
   public static int multiply(int i,int j) {
      int result=i*j;
      return result;
   }
}

Note the word static in our method declaration. Our "TestJava" class really doesn't need any special properties/instance variables so we might as well make all our methods static.

In the interactions panel, type the following:

Welcome to DrJava.
> TestJava.multiply(3,5)

NO SEMI-COLON. Press enter and you should see:

Welcome to DrJava.
> TestJava.multiply(3,5)
15

You can test it out with other numbers too. Now think about this: how would you write a method that computes the average of three numbers?

Comments

Comments are text that you write in your code that doesn't affect anything. Its purpose is just for you to write a little description for yourself and others who see your code to know what a variable means or what a method does. They are completely optional, but sometimes it is a good idea to include comments for complex methods, so you can better understand what is happening.

For comments that won't span more than one line, you use the double slash: //

For comments that will span multiple lines, you start with /** and for each line start with * and then finally end with */.
Examples:

// this is a one-line comment

/** this is
* a multiple
* line comment
*/

Let's think about what other math functions we can come up. Can you figure out how to write a method that will find the average of three numbers? Take a minute to think about this and don't look below!

Answer:

public static double average (int i, int j, int k) {
   int sum = i+j+k;
   return sum/3;
}

Confused? That's ok, let's go through it.
- public means the program user can access it
- static means we can access the method without first instantiating our class
- double means that the program will return a possible fraction (remember, it's the average, so it won't necessarily be an integer)
- average is the name of the method
- the i, j and k are the 3 numbers to represent the parameters
- in the actual method statements, we add the three numbers and return that value divided by 3!

 Part 4: Output [back to top]

Let's talk a bit about printing things. Sometimes you want methods that will print out some statement. This is different from a method that returns a String. We don't want a variable, we just want something printed. The syntax for this is:

System.out.println("text goes here");

If you have this in one of your methods, then whenever you call the method, it will print out what you specify. Basically, the syntax tells the system to output and print a line of text.

So let's create a simple method that uses this:

public static void print(String s) {
   System.out.println(s);
}

Now if you compile and run the program, type:

Welcome to DrJava.
> TestJava.print("Hello World!")
Hello World

...you should get that!

 Part 5: Conditionals [back to top]

Conditionals are situations where you want to check if something is true or not. This allows you to do something only if something else is true. For example, you'd only clean your room if it was dirty. You'd only roll the dice if it was your turn. You'd only get out of jail free in Monopoly if you rolled doubles, etc. So how, in Java, do we test if things are true or not?

if (condition) {
   //do something here
}

Any code you put within the parenthesis only gets excuted if the condition is true. Take a look at this:

if (3==5) {
   count = count+1;
}

This piece of code checks if 3 equals 5, and if so, then it increments our instance variable "count." Of course, 3 does not equal 5, so this code will never increment our count variable.

Say you have an instance variable in your Monopoly Simulator program called "inJail" that is false until you land in jail and then it becomes true. You want to check if you're in jail before you move your piece. If you are in jail, then you can't move. You would write this code as such:

if (!inJail) {
   //move piece
}

The exclamation point (!) is a way of saying not. It negates the condition, so if "inJail" is false, "!inJail" is true. That is, if you're NOT in jail, then you can move the piece.You can also write:

if (inJail==false) {
   //move piece
}

What if you want to check if multiple conditions are true? Two good things to know: "and" is written "&&" while "or" is written like "||" so if you want to check two things, you can write something like:

if (!inJail && isMyTurn) {
   //roll the dice
}

if (itsRaining || itRained) {
   System.out.println("It's wet");
}

 Part 6: Loops [back to top]

Ok, last thing. Loops. Loops are very very important. Loops are a necessity if you want to repeat a process several times and often in programming, you'll want to perform some task while some condition is true. Take a look at this:

int a = 5;
int count = 0;

while (a > 0) {
   count = count+1;
   a = a-1;
}

Can you see what this does?

It creates two integer variables "a" and "count" and creates a loop. While the value of the variable "a" is greater than 0, we increase "count" by 1 and decrease "a" by 1. Therefore, the first time the loop runs, "a" will decrease from 5 to 4 and "count" will increase from 0 to 1. Then the second time, "a" will decrease from 4 to 3 and "count" will increase from 1 to 2. This continues until "a" reaches 0 and then it is no longer greater than 0 so the loop will stop. Thus the final value of "count" will be 5.

This is useful in MANY situations. But here we will see how to write the multiply method explicitly, instead of using (*). The purpose of this is just simply to MULTIPLY but through the use of a loop so you can see how it works! It's nothing exceedingly complicated. We would write:

public static int explicitMultiply(int a,int b) {
   int result = 0;
   while (b > 0) {
      result = result + a;
      b = b - 1;
   }
   return result;
}

Understand this bit of code? Let's explain it. You start off with two numbers, a and b. Let's say a = 4 and b = 3. Then you create a number variable called "result" which will eventually have a value that is equal to a*b. But initially, it is set to 0. Then you start adding 4 to the "result" variable, 3 times. So first, result = 0, a = 4 and b = 3. Then you go through the loop one time. Now, result = 4, a = 4 and b = 2. Then you go again (since b > 0) and now, result = 8, a = 4 and b = 1. Go again and now result = 12, a = 4 and b = 0. Suddenly now b < 0 so the loop won't execute! So it stops, and returns the "result" variable, which now equals 12. This is, in fact, 4*3.

What this does is now when you input two numbers, it starts with 0 and adds "a" to itself "b" times. times. Try this out and you'll see that it does indeed act like a multiplier. If you're confused, just read through the code and try to understand what exactly is happening.

Another explanation: "result" is an integer value constantly changing (increasing) at a rate of "a." It increases by the value of "a" "b" times, since each additional "a" is a decrease in the value of b by 1 (hence, b=b-1) until b reaches 0. Thus, the loop has a termination point and explicitMultiply is defined.

Often times, in order to see what a bit of code does with a loop, you will have to play out the scenario in your head. That is, write down all the initial values of all the variables involved and then after one run of the loop, see what the new value of the variables are, then after a second run of the loop, etc. etc. and you should understand a lot more.

This style is called a while loop, and you can probably guess why. There's also another more-popular loop called the for loop. The syntax for one of these is:

for (int i = 0; i < 5; i++) {
   //do something
}

This has all three parts of the while loop all grouped together! It creates a counting variable "i" that gets incremented each time the loop runs - and the loop runs while "i" is less than 5. Using this method means you don't have to change the variable "i" in your code within the loop like you do for the while loop.

Convert this "while" loop into a "for" loop:

int i = 0;
while (i<5) {
   count = count*2;
   i++; }

Answer:

for (int i=0;i<5;i++) {
   count = count*2;
}

NOTE: The "i++" is a shorthand for incrementing the variable by 1. You could write i = i+1 OR you could write i++. It's just quicker that way. Similarly you can write "i--" etc.

 Part 7: Inheritance [back to top]

Sometimes, classes can inherit from others. That is, inherit certain instance variables and/or certain methods. Why would you want to do this? Well suppose you have a few different classes that all have some of the same methods, except they each have a few different methods. We could make one class for just those methods that they each have the same and then they can inherit from that class.

Interfaces

An interface is a class that has NO instance variables and whose methods are all UNdefined. That's right, there are no open/closed brackets {} - you just write the method name, specify the paremeters and then close with a semi-colon. For example, let's say we want to create a bunch of classes to represent Shapes. So, we might have an interface that has general methods that all our shape classes will have.

So here's our simple Shape interface:

public interface Shape {
   public double getArea();
   public void increaseSize(int n);
   public void decreaseSize(int n);
}

So note that every shape class we create can have these three basic methods, but they can be defined differently per class. Like, for a square, you get the area by squaring the side length, but for a circle, you square the radius and multiply by pi. THIS is why we don't define the methods in the interface - the interface just gives us the basic methods, but each of our classes define them themselves.

Say we now create a Circle class, but we add another method getRadius() which will return its radius. This is an example of a method that we CAN'T have in our interface, because what if we had a Square class? You can't get the radius of a square!

Here's how we have our Circle class "inherit" our Shape interface:

public class Circle implements Shape {
   private int radius;

   public Circle(int r) {
      radius = r;
   }

   public int getRadius() { return radius; }

   public double getArea() { return Math.pi*radius*radius; }

   public void increaseSize(int n) { radius = radius + n; }

   public void decreaseSize(int n) { radius = radius - n; }
}

So now, in our interactions pane, we can write:

Welcome to DrJava.
> Circle c = new Circle(3);

...and that will create a new Circle that has a radius of 3. We can also write:

> c.getRadius()
3
> c.getArea()
28.2743

Now we could write a Square class that has those three basic methods (and defines them correctly) and we could also add our own methods too (if we can think of some). The instance variable of our Square class would be like, private int sideLength; or something, since we only need to define one side length. If we were to create a Rectangle class, then we'd need two instance variables, one for the length and one for the width.

Abstract Classes

An abstract class is one that actually DEFINES the methods and can also have instance variables. This is for if we have a bunch of classes that all have some of the same methods that are defined the same way and/or if they all share the same instance variables with the same values.

So suppose we have a bunch of different animal classes like Cat.java and Dog.java. Each of these can inherit from a class called Animal.java, which has basic methods like getHungerLevel() or wakeUp() and instance variables like private int hungerLevel; and private boolean isAwake;. Methods and variables like these apply to both a dog and a cat and can be defined the same way in either class.

Here's our abstract Animal class:

public abstract class Animal {
   private int hungerLevel;
   private String name;
   private boolean isAwake;

   public Animal(String s) {
      name = s;
      hungerLevel = 0;
      isAwake = true;
   }

   public void wakeUp() { isAwake = true; }
   public void sleep() { isAwake = false; }
   public void isAwake() { return isAwake; }
   public String getName() { return name; }
   public int getHungerLevel() { return hungerLevel; }
}

Concrete, Abstract, Interface

Just a quick rundown:

  • a concrete class is any regular class with instance variables and methods and that can be instantiated (i.e. Circle c = new Circle())
  • an abstract class is almost like a regular class in that it can have instance variables and defined methods, but it can also have undefined methods like an interface. Regular, concrete classes extend abstract classes.
  • an interface has no instance variables, cannot be instantiated and has only abstract, undefined methods. Regular, concrete classes implement interfaces.

So, note that we've defined instance variables AND methods that really have nothing to do with whether our animal is a Dog or Cat - they're not very specific. So now let's create our Dog class.

public class Dog extends Animal {

   public Dog(String s) {
      super(s);
   }

   public void bark() { System.out.println("Bark!"); }
}

That's it! See, we don't have to write any other methods because they've already been defined in the Animal class. NOTE the use of "super" in the Dog constructor. That means we just have to refer to the superclass, that is, the class we are extending from, for the contructor. The Dog's constructor is the same as the Animal's so we can just use the Animal class's definition.

Also note that our abstract class looks just like a regular class, but it does have one main difference that hasn't been shown above: it can have abstract methods like the interface, that is, methods that are not defined.

In the interactions now we can write:

> Dog sam = new Dog("Sam");
> sam.bark()
Bark!
> sam.isAwake()
true

 Part 8: Arrays [back to top]

Suppose you want to store a bunch of items but you don't want to have to declare a separate variable for each. Suppose your AdventurePlayer character has a bag full of items but you don't want to have to create instance variables for thing1, thing2, thing3, etc. Well that's where arrays come in handy.

Arrays are basically like lists, but think of it more like a bunch of slots. Arrays hold a bunch of the SAME objects. That is, you can have an array of Objects, an array of ints, an array of Strings, etc. Note that arrays cannot have two different types of objects - they all have to be the same type.

When you declare an array variable, you use the open/closed straight brackets [ ] and you write them after you declare the type. So, for example, private int count; is a simple instance variable of type int while private int[] count; is an instance variable ARRAY of type int.

Then, to define an array, the syntax is much the same as you would define an object but you must specify the size of the array. Look at the syntax:

Welcome to DrJava.
> int[] c = new int[10];

This creates a new array called "c" that holds a bunch of ints and is of size 10 - it can hold 10 integers.

Now you can fill your array directly if you want by writing:

> c[0] = 3;

...which will make the first integer in our array, 3. The number inside the square brackets [] is called the index. Note that 0 is the first index - NOT one. Therefore, our last index in our array of size 10 is 9 - or array length - 1.

You can get the length of an array as such:

Welcome to DrJava.
> int[] c = new int[10];
< c.length
10

This is useful for using LOOPS to cycle through an array and do something with each item in the array. You start from the first index, 0, and go until the end of the array. Here is a loop that cylces through an array:

int[] a = new int[5];
for (int i=0; i<a.length;i++) {
   a[i] = i;
}

See what this does? We have a new array variable called "a" that is of size 5. We use a loop and cycle through each index of the array and fill it with its index value. That is, after this loop is executed, a[0] = 0, a[1] = 1, a[2] = 2, etc. Writing a[i] means that every time the loop runs, i will be incremented, so we will be accessing a different index in our array.

Recall our "average" method from Part 3. In that, we specified exactly 3 numbers in our parameters. Suppose we wanted a general average method that computed the average of anywhere from 2 numbers to 2 billion numbers. We certainly don't want to specify 2 billion parameters or even 10 for that matter! So how could we do this without that? Using an array! Take a look:

public double averageAll(int[] ourArray) {
   int sum = 0;
   for(int i=0;i<ourArray.length;i++) {
      sum = sum + ourArray[i];
   }
   return (sum/ourArray.length);
}

Our only parameter is some array of integers. This array can be of any size! We create a variable "sum" to hold the sum of all the numbers and we cycle through the array, each time adding to the sum the next number in the array. Then we divide this number of the array length - that is, how many numbers we've added - and return it.

If you need a solid example, suppose our array has 5 numbers, 4,6,8,10 and 12. After the first cycle of our loop, our sum is 4. Then after a second cycle, our sum is 10, then 18, then 28 and finally 40. Then we divide by 5 (since there are 5 numbers in our array) and we get 8, the average. Note that this averageAll method is of type "double" because our average may not necessarily be an integer.

So, how might you find the maximum of an array of integers? What's the algorithm for this? Let's take a look:

public int getMax(int[] a) {
   int max = a[0];
   for(int i=0;i<a.length;i++) {
      if(a[i] > max) { max = a[i]; }
   }
   return max;
}

...and there you have it. We create a variable to represent our maximum value and we start it off as the first number in our array. Then we go through our array number by number, and if any one is greater than our current max, then THAT number becomes our max, etc. until we finish the loop. Then we return our max number.

 Here's a Test! [back to top]

Create a class called Room to represent all the rooms in an adventure game. Each room has a name and a description, as well as a number of lucky charms. It also has a reference to the room just north of it and just south of it.

The Room class has the following methods:
- the constructor has a parameter where you can enter the name and description of the room, and sets the number of charms to 0.
- getName() which returns the name
- getDescription() which returns the description
- alterCharms(int k) which includes this parameter to specify the number of charms you want to ADD and adds that number to the current number of charms
- getCharms() which returns the number of charms
- getNorthRoom() which returns the room to the north
- getSouthRoom() which returns the room to the south
- setNorthRoom(Room n) which sets the north room to the room specified
- setSouthRoom(Room n) which sets the south room to the room specified

Hard? You know everything you need to know to do this!

Here are some sample interactions to help you test if you have written it correctly.

Welcome to DrJava.
> Room bar = new Room("bar","a smokey bar");
> bar.getDescription()
"a smokey bar"
> bar.getName()
"bar"
> bar.getNorthRoom()
null
> Room closet = new Room("closet","a broom closet");
> bar.setNorthRoom(closet);
> bar.getNorthRoom().getDescription()
"a broom closet"
> bar.getCharms()
0
> bar.alterCharms(3);
> bar.getCharms()
3

Click here for the solution.