Question

I'm trying to write a program that takes three sides of a triangle in any order, re arranges them in ascending order (a,b,c) and then tells the user what type of triangle it is and the area. However I can't figure out what is wrong with my code that it keeps getting the wrong true/false value for my isValid method. Even if the sides don't make up a triangle it still proceeds as if the isValid method had returned true. Any suggestions? Thanks.

package javaapplication1;

import java.util.Scanner;

public class Test
{

    public static void main(String[] args)
    {                                   

        Scanner input = new Scanner(System.in);

        System.out.println("Enter three numbers:");
        double a = input.nextDouble();
        double b = input.nextDouble();
        double c = input.nextDouble();

        if (a > b)
        {
            double temp = a;
            a = b;
            b = temp;
        }
        if (b > c)
        {
            double temp = b;
            b = c;
            c = temp;
        }
        if (a > b)
        {
            double temp = a;
            a = b;
            b = temp;
        }

        double area = area(a, b, c);
        boolean isValid = isValid(a, b, c);
        String type = type(a, b, c);

        if (isValid = true)
        {
            System.out.println("This triangle is " + type);
            System.out.printf("The area is %.2f", area, "\n\n");

        }
        else
        {
            System.out.print("Invalid triangle");
        }
    }

    public static boolean isValid(double a, double b, double c)
    {
        if (a + b > c)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static double area(double a, double b, double c)
    {
        double s = (a + b + c)/2.0;
        double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
        return area;
    }

    public static String type(double a, double b, double c)
    {
        String type;

        if (a == c)
        {
            type = "equilateral";
        } else if (a == b || b == c)
        {
            type = "isosceles";
        } else 
        {
            type = "scalene";
        }
        return type;          
    }
}
Was it helpful?

Solution

The issue appears to be here (unless it was a typo):

if (isValid = true)

You're assigning true to isValid, so the condition in the if statement is always true.

The proper way to do comparison of primitive values is by using two equals signs:

if (isValid == true)

However, for booleans, this is redundant. The best way to test if a boolean value is true/false is simply to use the boolean variable itself:

if (isValid)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top