shawn edward
shawn edward

Reputation: 149

Programming about finding the triangle

SOLVED

this is what I did so far:

class triangle
{
     public static void main (String[] args)
 {
System.out.println("Provide three side lengths - 000 to terminate.");
int a = In.getInt();
int b = In.getInt();
int c = In.getInt();

String output1 ="";
String output2 ="";


 while(a!=0 && b!=0 && c!=0)
{
   int biggest = Math.max(a, Math.max(b,c));
   int smallest = Math.min(a, Math.min(b,c));
   int middle = 0;


   if(a!=biggest && a!=smallest)
     middle = a;
   if(b!=biggest && b!=smallest)
     middle = b;
   if(c!=biggest && c!=smallest)
     middle = c;

   if(a==b && a==c && b==c)
   {
     output1 = "equilateral";
   }
   if((a==b && a!=c) || (a==c && a!=b) || (b==c && b!=a))
   {
     output1 = "isosceles";
   }
   if(a!=b && a!=c && b!=c)
   {
     output1 = "scalene";
   }

   int angle = (middle*middle) + (smallest*smallest);
   int angle2 = (biggest*biggest);

   if(angle == angle2)
   {
     output2="right";
   }
   if(angle > angle2)
   {
     output2="acute";
   }
   if(angle < angle2)
   {
     output2="obtuse";
   }

   System.out.println(output1 + " and " + output2);
   a = In.getInt();
   b = In.getInt();
   c = In.getInt();

   if(a==0 && b==0 && c==0)
   {
     System.out.println("Thanks for using the program");
     break;
  }

  }
 }
 }

My problem is that when I enter 5,2,5 it should be isosceles and acute but it comes out as isosceles and obtuse, and when I type 5,5,5 it comes out equilateral and right. The only one that works is if I enter 3,5,4 it will come out as scalene and right. I been at this for a while and my math looks correct. Can anyone help?

Upvotes: 1

Views: 80

Answers (2)

Instead of doing comparisons like you did, try to use Arrays.sort().

while (a != 0 && b != 0 && c != 0) {
    int[] sides = new int[]{a, b, c};
    Arrays.sort(sides);
    int smallest = sides[0];
    int middle = sides[1];
    int biggest = sides[2];

    //...
}

UPDATE:

Well, using max and min, you may try something like this:

int bigger = Math.max(a, b);
int biggest = Math.max(bigger, c);
int smaller = Math.min(bigger, c);
int middle, smallest;
if (smaller >= bigger) {
    middle = smaller;
    smallest = Math.min(a, b);
} else {
    middle = Math.min(a, b);
    smallest = smaller;
}

*notice that I did the sorting like having the semi-final of a soccer game.
I hope this may help you in learning logic. =)

Upvotes: 1

Barodapride
Barodapride

Reputation: 3723

Has to do with this logic:

   if(a!=biggest && a!=smallest)
     middle = a;
   if(b!=biggest && b!=smallest)
     middle = b;
   if(c!=biggest && c!=smallest)
     middle = c;

if you have two or more sides that are the same this will not work

Upvotes: 0

Related Questions