Pythagorean Test in Java

The following is a basic Java GUI program allowing a user to input the lengths of a triangle's sides to find out if it is a right triangle or not. Open notepad or any text editor, and paste in the following code:
  1. import javax.swing.*; //required for GUI components
  2. import java.awt.*; //required for use of the container
  3. import java.awt.event.*; //contains the ActionListener interface to handle GUI events
  4.  
  5. public class abc
  6. {
  7.     public static void main(String[] args)
  8.     {
  9.         double a, b, bc, c;
  10.         String aStr, bStr, cStr, output; //declares our variables
  11.        
  12.         aStr = JOptionPane.showInputDialog("Enter a length of the hypotenuse: "); //prompts user
  13.         a = Double.parseDouble(aStr); //sets a equal to the value input
  14.        
  15.         bStr = JOptionPane.showInputDialog("Enter a length of another side: "); //prompts user
  16.         b = Double.parseDouble(bStr); //sets b equal to the value input
  17.        
  18.         cStr = JOptionPane.showInputDialog("Enter a length of the last side: "); //prompts user
  19.         c = Double.parseDouble(cStr); //sets c equal to the value input
  20.  
  21.         bc = (b * b) + (c * c); //calculates the length of the two shorter sides squared
  22.        
  23.         if (bc == a * a) //conditional statement
  24.             output = "This IS a right triangle."; //output to user
  25.        
  26.         else //if conditional is not satisfied
  27.        
  28.             output = "This is NOT a right triangle."; //output
  29.            
  30.         JOptionPane.showMessageDialog(null, output, "Calculation", JOptionPane.INFORMATION_MESSAGE); //displays output in GUI window
  31.        
  32.     }
  33. }
Save it as abc.java. This is important or it will not run correctly. (The filename must match the name of the class that is delcared at the top.) You may notice there are a lot of comments. This is to help anybody who reads it know what each small section of code does. Read through this and you will get a feel for how it works step-by-step. Open a command line or terminal, and type "cd" (without quotes) followed by the path to where you saved the abc.java file. If you saved it in Documents, type "cd Documents" and hit enter. Now, type "javac abc.java" and hit enter, then "java abc" and the program will run. You will be asked for three lengths, starting with the hypotenuse. The program basically works by squaring the hypotenuse, and the sum of the other two sides, and seeing if both squares are equal. If they are, it is a right triangle. The user is told at the end if the sides they input make up a right triangle or not.

Add new comment