Triangle Perimeters. Go With The Flow.

| Posted in , , | Posted on 10:14 PM


This is another example of flow control. This is not at all an elegant program. It almost hurts me to post it. Hopefully as I become more comfortable with the language the flow will be nicer on the eyes. This program is a first for me because it tests the input and then asks the user if he/she would like to try again if the input is invalid. I used a while loop for test.



/*
 * This program takes the 3 lengths of a triangle's
 * sides, determines if these are valid lengths,
 * and then computes the perimeter.
 */

package perimeterofatriangle;
import javax.swing.JOptionPane;

/**
 * @author Neil master coder
 */

public class Main {


    public static void main(String[] args) {
       
        //initialize var for triangle sides
        int side1=0, side2=0, side3=0;
       
        //initialize var for continue question
        int question=0;

       
        while (question==0) {

            String stringSide1 = JOptionPane.showInputDialog(null,
                    "Enter the first side " +
                    "of the triangle.");
            String stringSide2 = JOptionPane.showInputDialog(null,
                    "Enter the second side " +
                    "of the triangle.");
            String stringSide3 = JOptionPane.showInputDialog(null,
                    "Enter the third side " +
                    "of the triangle.");

            side1=Integer.parseInt(stringSide1);
            side2=Integer.parseInt(stringSide2);
            side3=Integer.parseInt(stringSide3);

            if ((side1+side2
                (side2+side3
                (side3+side1

                String stringQuestion = JOptionPane.showInputDialog(null,
                        "The triangle you entered is invalid." +
                        " Do you want to try again? " +
                        "Enter 0 (zero) to continue or " +
                        "any other number to quit.");
                question=Integer.parseInt(stringQuestion);
                }
            else{
            if (question==0){
                JOptionPane.showMessageDialog(null, "The perimeter " +
                        "of a triangle having sides " +
                        side1 + " , " +
                        side2 + " and " +
                        side3 + " " +
                        "is " + (side1+side2+side3) +".");
                question++;
            }

        }


    }
    }
}

Comments Posted (0)

Post a Comment