2

I am new to coding and trying some assignments. I am trying to prompt a user for the lengths of the sides of a triangle. The program calculates the area and returns a value. I am trying to use a while loop to reprompt the user if the given lengths do not create a triangle.

While (true)
{
    SideA = parseFloat(prompt("Enter the length of Side A"));
    SideB = parseFloat(prompt("Enter the length of Side B"));
    SideC = parseFloat(prompt("Enter the length of Side C"));

    //Calculate half the perimeter of the triangle
    S = parseFloat(((SideA+SideB+SideC)/2));

    //Calculate the area
    Area = parseFloat(Math.sqrt((S*(S-SideA)*(S-SideB)*(S-SideC))));

    if(isNaN(Area)) 
    {
        alert("The given values do not create a triangle. Please re- 
           enter the side lengths.");
    } 
    else 
    {
        break;
    }   

}

//Display results
document.write("The area of the triangle is " + Area.toFixed(2) + "." 
+ PA);
1
  • while(!isValidTriangle(one, two, three)) { prompt("Enter lengths") }. Commented Jun 15, 2019 at 23:10

1 Answer 1

1

You can use a do while loop to achieve this:

function checkTriangleInequality(a, b, c) {
   return a < b + c && b < c + a && c < b + a;
}

function promptSides() {
  let a, b, c;
   while (true) {
    a = parseFloat(prompt("Enter a"));
    b = parseFloat(prompt("Enter b"));
    c = parseFloat(prompt("Enter c"));

    if (!checkTriangleInequality(a, b, c)) {
      alert("Input is invalid, please try again.")
    } else {
      let s = (a+b+c)/2
      let area = parseFloat(Math.sqrt((s*(s-a)*(s-b)*(s-c))));
      console.log(area);
      break;
    }
   }
} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I have this portion running smoothly. Where would be the ideal place to enter an alert that tells the user the inputs are invalid and to re-enter them? I do not want it to appear the first time it runs so I'm not sure how to make it work using this structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.