Reputation: 57
Ask the user for 2 sides of a triangle and then print out the length of the third side, as calculated by a method. Write a method to find the length of the third side using the Pythagorean theorem.
I'm new to java and I am suck with the following code which may be way off...
import java.util.*;
public class Tri8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = input.nextInt();
int b = input.nextInt();
System.out.println(pythagoraen(a, b));
}
//Method goes here
public static int pythagoraen(int x, int y) {
Math.pow(x, y);
int z = Math.sqrt(x, y);
Math.sqrt(x, y);
}
}
Upvotes: 0
Views: 3807
Reputation: 310983
Assuming you meant to find the hypotenuse of a right-angled triangle using the pythagorean theorem, you need to return the root of the sum of squares of both other sides:
public static double pythagoraen(int x, int y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
Upvotes: 2
Reputation: 436
private static double pythag(double x, double y){
return Math.sqrt(x*x + y*y);
}
or if you want to use math.pow, you can replace x*x with Math.pow(x, 2)
in java calling math.sqrt and math.pow dont directly edit the variables, they actually return a value that you can use, for instance math.pow takes in two double, the first is the base and the second is the exponent, so Math.pow(2,3) would be the same to you and me as 2^3
Upvotes: 1
Reputation: 461
Here's the fixed code:
import java.util.*;
public class Tri8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers:");
int a = input.nextInt();
int b = input.nextInt();
System.out.println(pythagoraen(a, b));
}
//Method goes here
public static int pythagoraen(int x, int y) {
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
}
}
Upvotes: -1