Question

The code below is supposed to analyze the type of a triangle based on the angles entered by the user in the terminal. However, in the first if statement although I set it to (a+b+c==d) - still, in the terminal if I enter 180, 1, 1 - instead of stopping the execution and printing Triangle is not possible., it instead says the triangle is isosceles. It's surely a mistake on my part. But I am a noob, so please correct my statements.

/**
 * @date 20/4/2014
 */ 


import java.io.*;
public class Triangleanglederivation
{
       public static void main (String args[])throws IOException
    {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        int a,b,c,d; 
        d=180;
        System.out.println("Enter the three sides of the triangle:");
        a=Integer.parseInt(in.readLine());
        b=Integer.parseInt(in.readLine());
        c=Integer.parseInt(in.readLine());        
        if(a+b+c==d)
            System.out.println("Triangle is possible.");    
        if((a==b)&&(b==c)&&(c==a))
            System.out.println("The triangle is equilateral.");
        else if((a==b)||(b==c)||(c==a))
            System.out.println("The triangle is isosceles.");
        else if((a!=b)&&(b!=c)&&(c!=a))
            System.out.println("The triangle is scalene.");
        else
            System.out.println("Triangle is not possible.");
    }
}

Fix

if((a==b)&&(b==c)&&(c==a)&&(a+b+c==d))
  System.out.println("The triangle is equilateral.");
else if(((a==b)||(b==c)||(c==a))&&(a+b+c==d))
  System.out.println("The triangle is isosceles.");
else if((a!=b)&&(b!=c)&&(c!=a)&&(a+b+c==d))
  System.out.println("The triangle is scalene.");
else
  System.out.println("Triangle is not possible.");
Was it helpful?

Solution

Your checks for the triangle being equilateral, isosceles, and scalene are being applied regardless of whether the triangle is possible or not. You need to either add the possibility check (a+b+c==d) to each of those using && or nest the if/else such that they only happen when the if (a+b+c==d) has succeeded.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top