HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Triangle Type Program

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
typetriangleprogram

Problem

Is there any way to simplify it further?

import java.util.*;

class Triangle {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

        if(a==b && b==c)
            System.out.println("Equilateral");

        else if(a >= (b+c) || c >= (b+a) || b >= (a+c) )
            System.out.println("Not a triangle");

        else if ((a==b && b!=c ) || (a!=b && c==a) || (c==b && c!=a))
            System.out.println("Isosceles");

        else if(a!=b && b!=c && c!=a)
            System.out.println("Scalene");
    }
}

Solution

Is there any way to simplify it further?

Sure, but what's more important: Create some useful methods. Your class is single shot only: read data, classify, output. This is a bad start, a method should do one thing only. So you need three methods.

You classify into 4 categories and this is a clear case for an enum:

enum TriangleType {
    EQUILATERAL, INVALID, ISOSCELES, SCALENE
}


This is the only interesting method:

static TriangleType classify(int a, int b, int c) {
    if (a = b+c || c >= b+a || b >= a+c) return INVALID;
    if (b==c || a==b || c==a)) return ISOSCELES;
    return SCALENE;
}


Note that I'm violating the "braces everywhere" rule. I can't help myself.

In case of ISOSCELES, there's no need for checks like a==b && b!=c as we already know that not all sites are equal.

In case of SCALENE, there's no need for any test, as we know that there are no two equals sides.

You're using a bit too many parentheses, but feel free to keep them if you feel you need them.

Be consequent with your spacing, there are rules for it, which help to make it more readable:

  • single space between "if" and "("



  • (but no space between a method name and "(")



  • no space after "("



  • no space before ")"



The addition is subject to overflow as Ryan noted, but let's ignore it for now. You should know about it and do a corresponding test if needed, but in general, overflow is impossible to check for everywhere.

Here it's trivial, just replace a >= b+c by a >= (long) b+c. The latter means a >= ((long) b) + c, which is equivalent to ((long) a) >= ((long) b) + ((long) c).

Code Snippets

enum TriangleType {
    EQUILATERAL, INVALID, ISOSCELES, SCALENE
}
static TriangleType classify(int a, int b, int c) {
    if (a <= 0 || b <= 0 || c <= 0) return INVALID; // added test
    if (a == b && b == c) return EQUILATERAL;
    if (a >= b+c || c >= b+a || b >= a+c) return INVALID;
    if (b==c || a==b || c==a)) return ISOSCELES;
    return SCALENE;
}

Context

StackExchange Code Review Q#62891, answer score: 9

Revisions (0)

No revisions yet.