CMSC 206 (Introduction to Computing)
Assignment#0 (ungraded)
No due date since it will not be
submitted, but you should complete this assignment by the end of the
first week of class.
The purpose of this assignment is to
get you started in writing programs in Java. As such, you should
complete this assignment by the end of the first week of classes.
Also, since we are just starting out, this assignment is
ungraded. In fact, you will not even be submitting this
assignment. It is purely for your benefit. Because of this,
you are welcome to work with other students in the class to complete
this assignment.
Write a program that reads a positive
integer n from the command
line and prints out the
squares of all numbers 1 through n.
Here are some example traces of running
this program:
> java Assignment0 4
1 4 9 16
> java Assignment0 -4
Error: input
"-4" is not a valid positive integer
Usage: java Assignment0 <positive integer>
> java Assignment0 3.14
Error: input "3.14" is not a valid positive integer
Usage: java Assignment0 <positive integer>
> java Assignment0 CMSC206
Error: input "CMSC206" is not a valid positive
integer
Usage: java Assignment0 <positive integer>
>
java Assignment0
Error: no input given
Usage: java Assignment0 <positive integer>
Notice that the bulk of the program will consist of error checking the
input. What do you think should happen if the user specifies more
than one input?
The first thing you should try to run is the basic HelloWorld
program, given below:
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!
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.
// When first developing your program without error checking, this is
the only line you need.
} catch (Exception e) {
// code that is here is executed if the conversion
fails, which is useful for error checking
}
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.