In this question, you will write a program that reads two integers as command-line arguments and calculates the distance between them. We will define this distance in the standard arithmetic manner, namely as the difference between the larger and the smaller of the two numbers.
For example:
A | B | Distance |
---|---|---|
1 | 10 | 9 |
10 | 1 | 9 |
6 | 4 | 2 |
4 | 6 | 2 |
5 | 5 | 0 |
You will calculate this distance in two ways:
- Using the methods Math.min() and Math.max().
- Using the methods Math.abs().
As in the Week 1 Lab Exercise, you will make a class, this time called Distance1. You will also need to create a main() method, i.e. with the declaration:
public static void main( String[] args ){ ... }
As previously, we will need to read two integers from the command line, using the method Integer.parseInt(), and then store the values in variables.
In order to calculate the larger and smaller of the two values, the Java Math library provides the methods Math.max(int a, int b) and Math.min( int a, int b). For example Math.max(1, 4) would return 4, whilst Math.min(12, 45) would return 12.
Your program should print out the result of subtracting the smaller number from the larger one.
An automated test has been created for this exercise: Distance1Test.java.
An alternative way to calculate this distance is to subtract the first number, whatever it is, from the second number. We can then see if this result is positive or negative.
- if it is positive, we use that number as the distance
- if it is negative, we invert the sign so it is positive and use that number as the distance.
Java provides a method for performing this calculation, namely Math.abs() (absolute value).
x | Math.abs(x) |
---|---|
1 | 1 |
2 | 2 |
100 | 100 |
-1 | 1 |
-2 | 2 |
-100 | 100 |
Write a class, Distance2, which use the Math.abs() method instead of the methods Math.min(), Math.max() to calculate the distance between the two command line arguments.
An automated test has been created for this exercise: Distance2Test.java.