Skip to content

Instantly share code, notes, and snippets.

@gpiancastelli
Created February 22, 2013 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gpiancastelli/5015302 to your computer and use it in GitHub Desktop.
Save gpiancastelli/5015302 to your computer and use it in GitHub Desktop.
Classify a triangle given the length of its three sides as input.
package com.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class TriangleDemo {
public static final int INVALID = -1;
public static final int EQUILATER = 1;
public static final int ISOSCELES = 2;
public static final int SCALENE = 3;
private static final List<Integer> TYPES = new ArrayList<Integer>(3);
static {
TYPES.add(EQUILATER);
TYPES.add(ISOSCELES);
TYPES.add(SCALENE);
}
public static int triangle(int a, int b, int c) {
int[] sides = {a, b, c};
Arrays.sort(sides);
if (sides[0] + sides[1] <= sides[2]) {
return INVALID;
}
Set<Integer> differentSides = new HashSet<Integer>();
differentSides.addAll(Arrays.asList(a, b, c));
return TYPES.get(differentSides.size() - 1);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String line;
do {
System.out.println("Type three numbers separated by a space: ");
line = input.nextLine().trim();
if (line.isEmpty()) {
break;
}
String[] sides = line.split("\\s+");
int triangle = triangle(Integer.parseInt(sides[0]),
Integer.parseInt(sides[1]),
Integer.parseInt(sides[2]));
String message = "The triangle is: ";
switch (triangle) {
case EQUILATER:
message += "equilater";
break;
case ISOSCELES:
message += "isosceles";
break;
case SCALENE:
message += "scalene";
break;
default:
message += "invalid";
}
System.out.println(message);
} while (!line.isEmpty());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment