/home/wpollock1/public_html/AJava/Triangles/Triangles.java
package com.wpollock.triangles;
import java.util.Arrays;
/**
* Triangles is a stand-alone console application that reads three integer
* values from the console. The three values represent the lengths of the sides
* of a triangle. The program prints a message that states if the triangle is
* equilateral (all sides the same length), isosceles (two sides the same
* length), or scalene (all sides have different lengths).
*
* @author wpollock
*/
public class Triangles {
/**
* main method. To facilitate testing, the work is done by a method
* that returns a Sting result.
*
* @param args command line arguments
*/
public static void main(String... args) {
try {
System.out.println(classify(args));
} catch (Exception e) {
System.err.println("Arguments must be three integers, "
+ "representing the sides of a valid triange.");
}
}
/**
* Classify takes three strings representing integers, and determines the
* type of triangle they make.
* This is demo code only, and contains a deliberate (but subtle) error!
*
* @param args An array of three Strings, representing the integer sides
* of a valid triangle.
* @return A String, one of "Equilateral", "Isosceles", or "Scalene".
* @throws IllegalArgumentException If arguments are not three Strings
* representing the integer sides of a valid triangle.
*/
public static String classify(String... args) {
if (args.length != 3) {
throw new IllegalArgumentException("Must have three arguments");
}
long[] side = new long[3];
// Integer.parseUnsignedInt is new since Java 8:
side[0] = Integer.parseUnsignedInt(args[0]);
side[1] = Integer.parseUnsignedInt(args[1]);
side[2] = Integer.parseUnsignedInt(args[2]);
// Check for valid side lengths:
if (side[0] <= 0 || side[1] <= 0 || side[2] <= 0) {
throw new IllegalArgumentException(
"Arguments must be greater than zero");
}
// Check for valid triangle. The sum of the two shorter sides must
// be greater than the longer side (try to spot the logic error):
Arrays.sort(side);
if ( side[0] + side[1] <= side[2] ) {
throw new IllegalArgumentException(
"No triangle is possible with sides of "
+ Arrays.toString(side) );
}
// Determine the type (try to spot the minor logic error below):
if (side[0] == side[1] && side[1] == side[2]) {
return "Equilateral";
} else if (side[0] == side[1]
|| side[1] == side[2]
|| side[0] == side[2]) {
return "Isosceles";
}
return "Scalene";
}
}