CMSC 206 (Data Structures)
Assignment#1
Due:
September 12, 2012 by 11:59pm
Due: September 14, 2012 by 11:59pm
The purpose of this assignment is to get
you started in writing programs in Java.
Write a program that reads a list
of integers from the command line and prints out the min, max,
and mean of the list.
Here are some example traces of
running this program:
> java Assignment1
2 4 6
Min: 2
Max: 6
Mean: 4
> java Assignment1
-4 0 -9 2
Min: -9
Max: 2
Mean: -2.75
> java Assignment1
3.14 2 4 90
Error: input "3.14" is not a valid
integer
Usage: java Assignment1 <list of
integers>
> java Assignment1
CMSC206
Error: input "CMSC206" is not a
valid integer
Usage: java Assignment1 <list of integers>
> java Assignment1
Error: no input given
Usage:
java Assignment1 <list of integers>
Notice that much of the program
will consist of error checking the input.
The first thing you should try to run is the basic HelloWorld
program, given below:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Copy this code into a file called HelloWorld.java and the compile it using the
following command:
>
javac
HelloWorld.java
This command should produce the file HelloWorld.class, which
is the compiled Java program. You can then run the
HelloWorld program by:
> java HelloWorld
Hello World!
Once you have HelloWorld working, here are some suggested steps to develop your assignment. Make sure you have a working program (debugged and tested) at the end of each step before moving to the next. Document your code as you go with comments.
System.out.println("This
is a normal output message.");
System.err.println("This is an error message.");
System.exit(1);
// the number (in this case 1) denotes a status
code. By convention, exiting with a code of 0
indicates normal termination, and anything else
denotes some error. Different errors can use
different status codes.
int n; //
why do we need to declare n outside of the try-catch
statement?
try {
n =
Integer.parseInt(str); // This line extracts the
integer from the String variable str and stores it in
n.
} catch (Exception e) {
// code that is here is executed if
the conversion fails, which is useful for error checking
}