Java Fundamentals  «Prev  Next»

Creating Prime Application - Exercise

Creating the Prime application

Objective: Create a command-line application to determine whether a number is prime.

Exercise grading

The full credit for this exercise is 15 points. To receive full credit, you will need to successfully create the source code for the application. You will submit your source code.

Exercise Instructions

Create a command-line application named Prime that determines if the integer provided by the user is a prime number. A prime number is an integer greater than 1 that is divisible by only 1 and itself. The first ten prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29.
One strategy you can use to complete this exercise is to create a static method isPrime() that accepts an int parameter and returns a boolean value representing whether or not the parameter is a prime number. Here is an algorithm you can use for your isPrime() method:

If the number is less than 2 return false
If the number is equal to 2 return true
If the number is divisible by 2 return false
Loop through the odd numbers from 3 to the square root of the number
If the number is divisible by the loop index
Return false
Return true

To find the square root of a number you can use the static method sqrt() from the class Math. Here is an example:
double x = Math.sqrt(25.0);

In this application you will need to convert a command-line argument from a String to an int. The static method parseInt() in class Integer provides this functionality. Here is an example of parseInt() in action:

String s = new String("123");
int    n = Integer.parseInt(s);

In your main() method, if the user does not supply exactly one command-line argument, display a usage message and exit the application. Make sure you test your application with a variety of integers.

What to submit:

In the text box below, cut and paste the source code for the Prime application.
Click, Submit to submit your code to the course .