Back to the Program-A-Day homepage
Problem
Create a program that will allow the user to enter in the lengths of two sides of a right-angled triangle, and will output the length of the triangle's hypotenuse. The two sides should be entered using two consecutive JOptionPane.showInputDialog boxes, and the result should be given using System.out.println. The input should be taken as two positive decimal values. Assume valid inputs.
The formula for calculating the hypotenuse is <math>a^2 + b^2 = c^2</math>, where a and b are the two sides, and c is the hypotenuse.
To solve this problem, you will need to understand:
Sample Input: 3,4
Sample Output: 5.0
Sample Input: 2.5,2.5
Sample Output: 3.5355339059327378
|
|
SideSectionTitle
|
Solution
The solution...
For the entire code solution, see below.
|
Code
Solution Code
/* Class Pythagoras
* Created by Brendan Curran-Johnson
* Made in COMP3040
* Takes the two sides of a triangle and outputs the hypotenuse
*/
// Need this for JOptionPane
import javax.swing.*;
import java.lang.Math;
public class Pythagoras
{
public static void main (String args[])
{
// These variables are used for input
String input;
double sideA;
double sideB;
// Get input 1
input = JOptionPane.showInputDialog(null, "Please enter the first side of the triangle");
// Convert string to double
sideA = Double.parseDouble(input);
// Get input 2
input = JOptionPane.showInputDialog(null, "Please enter the second side of the triangle");
// Convert string to double
sideB = Double.parseDouble(input);
//calculate A^2
double sideA2 = Math.pow(sideA, 2);
//calculate B^2
double sideB2 = Math.pow(sideB, 2);
//calculate C^2
double sideC2 = sideA2 + sideB2;
//calculate C
double sideC = Math.sqrt(sideC2);
//output solution
System.out.println("The length of the hypotenuse is: " + sideC);
}
}
|
Back to the Program-A-Day homepage