Download Creating, Compiling, and Running Java programs

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Creating, Compiling, and Running Java programs
with TextPad and text editors.
Welcome to CS103. The first task today will be to write your first Java program. This lab sheet will help
you step through the process of creating your own program, compiling it, and executing the program using the
TextPad program. If you would like to use another text editor and a command line program (like DOS), please see
the appendix A for how to compile programs outside of the Integrated Development Environment (IDE) available in
TextPad. Information regarding common error messages and their usual solutions can be found in Appendix B.
Appendix C holds the source code for NumberGuess.java, the program for (and subject of) today's lab.
1. Writing the Program
The first thing to do is open up the TextPad program. You will find it in Start->Programs->TextPad (the ->
symbol means to go down the next level of the menu). Though there may be some different programs in your start
menu, it should look something like this:
Once you have opened the program, type or copy (recommended, use Ctrl+C) the NumberGuess.java from
Appendix C into the Main Text Window. Be careful to type exactly what is in the program. Remember, Java is case
sensitive, so even the capitalization of words and variables must match ("System" and "system" are not the same
thing in Java). Once you have the whole program entered, you will want to save the file. You can either press Ctrl+s
(the Ctrl key and the "s" key at the same time) or use the Save command under the File menu (File->Save or File>Save As). Again remember that the file name must match that of your public class (If it says "public class
NumberGuess" at the top of the file, then your filename should be "NumberGuess.java"). Make sure when saving
that the Java option is selected or that you end your file with the .java extension (If you have the Java type selected
you don't need to add the .java extension. It will be added automatically for you). Your Save screen should look
something like this (though instead of the file “Hello.java”, your file should be called “NumberGuess.java”):
2. Compiling
Once you have saved the program, it is time to try and compile the program. This will create a new .class
file ("NumberGuess.class") that contains binary codes that are easier for the computer to understand than the text
you printed into the NumberGuess.java file. Before compiling the program, make sure to copy the SavitchIn.java
file into the same directory as your NumberGuess.java. You can find the SavitchIn.java file on the class website at
http://www.cs.uaf.edu/~cs103/java/SavitchIn.java or get it off the CD from the back of the book. To compile the
program, go to the Tools menu and select "Compile Java" or just press Ctrl+1. It should look something like this:
If your file was completely correct and contained no typos, then you should get no messages and it will
return back to your program. If you do get messages, then that means there are compiling errors in your program
that you need to go back and fix. For a list of common error messages and their likely solutions, see appendix B.
3. Executing
After a successful compilation, you can run your program. To do this, select either "Run Java Application"
or press (Ctrl+2). The menu looks as below. If all goes well, you will get a command window that is running your
program. Once the program is finished, it will tell you to press a key to continue. If there are more errors reported
when you try to run your program, then there are some "run-time errors" in the program file. For a list of common
run time error messages and their usual solutions, see Appendix B.
Congratulations, you have just completed your first Java program.
Appendix A- Compiling and running Java Programs outside of TextPad
If TextPad is not available on the machine you are working on, you can still create Java programs assuming
that you have Sun's Java Software Development Kit (SDK) installed on the computer (in fact, even TextPad requires
the SDK to be installed for it to be able to compile and run the programs). To get Sun's Java SDK (there are also
other Java SDKs but Sun is the de facto standard), go to http://java.sun.com/j2se/1.3/ to download and install the
SDK. The web pages located at www.java.sun.com are actually really good resources for all things Java. Once you
have the SDK installed on the machine, all you need is a text editor (such as Word, Notepad, WordPad, vi, or edit)
and a command line prompt. On a Windows 9x/ME machine you can get a command line prompt by going to Start>Run and typing in the word "command". On a Windows NT/2000 machine, you go to Start->Run and type in
"cmd". Use your text editor to save your Java program (make sure it ends in the extension .java and has the same
name as the class inside the file). Then go to your command line prompt. It should look something like this:
Once your are using your command line prompt, you will need to get to the same directory as the Java
program you just saved ( use the change directory command "cd"). You may also need to change your system PATH
variable to include the \bin and \jre\bin directories of your SDK installation (usually located at C:\jdk1.3\bin and
C:\jdk1.3\jre\bin, email me at [email protected] if you are having problems with this). Once both of these conditions
are satisfied, you are ready to compile.
To compile a program NumberGuess.java enter the following text at the command prompt:
javac NumberGuess.java
Be sure to include the .java extension in that command. At this point you will either get error messages
which you will have to deal with before continuing (see Appendix A) or you will get no messages and another
command prompt will appear. If you look in that directory, you will also now notice a file called NumberGuess.class
(after a successful compilation). Now, to run the program, enter the following at the next command prompt:
java NumberGuess
Be sure this time to not include the .java or .class extension in that command. This command will call the
Java Virtual Machine to run the file NumberGuess.class. If everything was correct in you program, it will execute
and output to your screen. If there are still some run-time errors you will need to sort those out (see appendix B).
These two commands, javac and java, are the only two you will need to compile and run any regular Java
program, respectively.
Appendix B- Common error messages and their usual solutions
Compile-Time Errors
Message:
C:\WINDOWS\Desktop\Text.java:2: 'class' or 'interface' expected
public static void main(String [] args)
^
Solution:
Probably forgot to enclose the main (String [] args) function inside of
a public class (that has the same name as the file!). Insert your main
function in place of the ellipses (...) in the following text (for a file
named Text.java):
public class Text
{
...
}
Message:
C:\WINDOWS\Desktop\Text.java:5: ';' expected
System.out.println("Howdy")
^
Solution:
This is probably one of the most common errors in programming. You just
forgot the semi-colon to end the instruction. Put a semi-colon at the end of
the line.
Message:
C:\WINDOWS\Desktop\Text.java:5: cannot resolve symbol
symbol : class out
location: package system
system.out.println("Howdy");
^
Solution:
Java is a case-sensitive language, so you need to be careful of whether
a class, object, or variable is capitalized or not. The word "system" here
should be capitalized. The statement should read:
System.out.println("Howdy");
Message:
C:\WINDOWS\Desktop\Text.java:1: class Eric is public, should be declared in a
file named Eric.java
public class Eric
^
Solution:
If a file is called Text.java it must have a public class Text declared
somewhere inside of it(see the first error message of this section for a
correct example). The public classes in a file have to have the same name as
the file (thus only one public class per file).
Message:
C:\WINDOWS\Desktop\Text.java:7: '}' expected
}
^
Solution:
Curly brackets need to be matched up. For every opening bracket "{" you
need a closing bracket "}". You have probably forgotten a closing bracket
somewhere.
Message:
C:\WINDOWS\Desktop\Text.java:1: '{' expected
public class Text
^
Solution:
Another curly bracket problem. This time, the curly brackets that
surround the definition of a public class seem to have been forgotten (or at
least the beginning one has).
Message:
C:\WINDOWS\Desktop\Text.java:5: cannot resolve symbol
symbol : method println (java.lang.String)
location: class java.lang.System
System.println("Howdy");
^
Solution:
The proper statement for outputting text to the screen is
System.out.println("Howdy");
Run-Time Errors:
Message:
Exception in thread "main" java.lang.NoSuchMethodError: main
Solution:
The Java Virtual Machine could not find the correct method to start the
program. Java requires that the program always start in a main function that
is declared like so:
public static void main(String [] args)
If your main declaration looks correct, also make sure that your class
has been declared public.
Appendix C: NumberGuess.java source code
public class NumberGuess
{
public static void main(String args[])
{
int answer; // random number to be guessed by user
int count; // running count of the number of guesses the user has taken
int guess; // current number guessed by user
int limit; // maximum number of possible guesses allowed
int max;
// maximum number in the range
int min;
// minimum number in the range
// initialize variables
max
= 100;
min
= 1;
limit = 20;
answer = (int)(Math.random() * max) + min;
// prompt user to enter their first guess
System.out.print("Guess a number in the range [" + min + " - " + max + "]: ");
// initialize attempt counter
count = 0;
// read in guess and check if user guessed correctly
do
{
// count the number of attempts
count++;
// read in guess
guess = SavitchIn.readLineInt();
if (guess > answer)
System.out.println("Too High!");
else if (guess < answer)
System.out.println("Too Low!");
else
break;
if (count < limit)
System.out.print("Guess again: ");
}
while (count < limit);
// display appropriate (win/lose) response to user
if (count == limit)
{
System.out.println("\nSorry, maximum number of attempts exceeded :(");
System.out.println("The number was: " + answer);
}
else
{
System.out.println("\nCongratulations!");
System.out.println("You correctly guessed the number in only " + count + " attempts.");
}
System.out.println();
}
}