With a few exceptions, you already know everything you need to in order to write any program there is. However, even when you have a good handle on each part of programming, putting them all together can seem a little overwhelming.
What follows is a few possible outlines of how to put the pieces together. These how-tos are not the only way to program, of course, and you will develop your own style with experience, but they can be a good fall-back when you get stuck.
How to Design a Program and Write Classes
How to Write a Method
How to Write a Loop: Top-Down or Bottom-Up
Imports, Filenames, and other Java Trivia
Confusing Error Messages
This discusses how to take an idea and from it create a set of classes and identify their methods. If you just want to write a single class, skip to Step 4.
If you
Horse
is likely to be one of your types.File
s, URL
s, and/or Scanner
s? If you need the program to react to something on a GUI, each of the things it reacts to is some type of event: ActionEvent
for buttons, MouseMotionEvent
for the mouse moving, etc. List any events you think might be needed, even if you don't know what name Java gives them; we can sort that out later.char
, int
, double
, boolean
, or String
?ArrayList
works if you want a variable-length list you can add to and remove from.HashMap
stores pairs of values, like a phone book pairing names with telephone numbers.SomethingTester
(in a file SomethingTester.java) where
Something
is replaced by your program's name. Give it only one method: an empty public static void main(String[] args)
private
attribute declaration for it. If it is some strange type, you may have to write the class for that type first….getThing()
and setThing(ThingType thingValue)
methods. Typically these should be public
and contain little more than return this.thing
or this.thing = thingValue
, possibly with some if
statements to check for illegal values.gang of 3:
toString
, clone
, and equals
.this.setThing
methods.SomethingTester
class's main
method, add some code that makes a few new ClassYouJustWrote(…)
objects, calls a few of the get/set methods, and prints out the results. Don't move on until those printouts look the way you expected them to look.// methods I need to write:
.main
method in SomethingTester
that calls the method you wrote and prints the results.Suppose you're writing a method inside class Foo
(Why Foo
? It's a traditional nonsense-name… see Wikipedia or RFC 3092).
public
.class Foo
, you get one free Foo
object via the this
variable; if you don't need a Foo
object, or if Foo
isn't even a type, make the method static
to prevent this
from being provided.Foo
s beyond the one free this
, need to be arguments to the method.this
or one of the parameters) in-place?void
method.
this.
or Foo.
where appropriate. Java will insert these silently if you forget them, but that might not do what you wanted to do.baz(…)
from within method baz(…)
(or new Foo(…)
from inside constructor Foo(…)
) is recursion, and unless you intended to make a recursive method it is almost always the wrong thing to do.x = this.getThing()
instead of x = this.thing
and this.setThing(x)
instead of this.thing = x
. You don't have to, but it'll make your life easier when you need to prevent invalid assignments or change the representation of the object later.return something;
statement. If it's a void
method, it can have empty return;
statements if you want, though it doesn't need them.what's the first thing I just did?
Before you write a loop, make sure you need to write a loop. Loops do (nearly) the same thing many times in a row. There are two basic approaches to writing loops, either one of which should work:
The top-down approach starts with the idea that there is a loop and fills it in from there.
If I were doing this as a human, what would I be repeating?Write down the answer (in English) between curly braces (
{
and }
).How many times do I repeat it?If the answer is
for(int i = 0; i < n; ++i)
loop.for
loop as you would for any number.ArrayList
, or HashMap
, try the iterator loop for (X element : Y)
.Scanner
, try a while ( Y.hasNextX() )
loop.As long as X is true(or
until X becomes false): use a
while ( X )
loop.for
if you used a for
loop.The bottom-up approach delays adding the loop until it is clear what it will look like.
what changed between those three repetitions?
while (guard)
loop. The guard ought to answer the question How can I tell if I need to do this again?
for (int i = 0; i < guard; ++i)
loop. See if you can rewrite the lines to express the changing numbers in terms of i
(counting up from something other than zero? Try i + start
. Counting down? start - i
should work). The guard should be the number of times the loop should run.Is that it, or will something else change eventually?If something else'll change, you'll probably want to put the loop you just wrote inside another loop. Write out the first three ways this loop will appear and repeat the process outlined above.
public class SomeRandomClassName
should start with a capital letter and must be in a file named SomeRandomClassName.java, with the same capitalization as the class name.
cannot find symbol symbol: class JFramewhen you compile, but you know
class JFrame
exists, you probably need an import statementjava 1.6 api ClassIWantToFind)
Class NameOfThisParticularClassin large text near the top of the page; right above that in small bold print will be where this package that defines this class.
Class JFramethe line
javax.swing, so we add to our java file
import javax.swing.*;
.public class …
line in our .java file.import
must come before class
; the order of the parameters of a method and the statements inside a method is also significant.As a reminder, the number of compiler errors java gives is more or less meaningless. Fix the first one, then recompile.
Some error messages ar every long. The top is usually more important than the bottom of such messages. The first line tells you what went wrong; the rest tells you where it went wrong.
add
on a HashMap
).}
s before that line.}
or )
before that line.}
, usually one missing on the last line of the file.ArrayList
or HashMap
. The error message should include a long list of the same filename:linenumber, which is the line that caused the problem.FileName.java:lineNumber: unreported exception package.name.SomeNewException; must be caught or declared to be thrown. Go to that file and that line of the file, scroll up to the method that encloses that line, and add
throws SomeNewException
between the )
that ends the argument list and the {
that begins the body of the method. If there already is a throws
line there, add your exception to the list, as throws OldException, SomeNewException
.Prepared by Luther Tychonievich for CS1112 at UVa, 15–19 April 2010