Sunday, September 10, 2017

Math.sqrt + DecimaFormat

Challenge: Write a program that computes the length of the hypotenuse of a right triangle. The program will prompt the user first to enter the lengths of the other two sides of the triangle. Round your output to one decimal place (use the DecimalFormat class). 

Solution:

import java.util.*;
import java.text.*;

class lab3_4{

public static void main (String[]args)
{


Scanner in=new Scanner(System.in);
double x;
double y;
double totalValue;





System.out.println("Enter one length of the triangle: ");
x=in.nextDouble();
System.out.println("Enter the other length of the triangle: ");
y=in.nextDouble();
//(Math.pow(x1-x2,2)+Math.pow(y1-y2,2));
totalValue = Math.sqrt(Math.pow(x,2)+Math.pow(y,2));

DecimalFormat dFormat = new DecimalFormat ();
dFormat.setMaximumFractionDigits(1);
//System.out.println("Area = " + totalValue);
System.out.println(" The length of the hypotenuse is: " + dFormat.format(totalValue));

//System.out.printf("The length of the hypotenuse is: %.1f",totalValue);
System.out.print("\n");

}
}

No comments:

Post a Comment