Calculate third side of a triangle using methods - java

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);
}
}

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));
}

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

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));
}
}

Related

Java Return is Returning Blank

I'm trying to create a java method that returns the sum of two values x and y. Currently when I run the code, the output isn't returning anything. Is there any way I can get the value to return the sum WITHOUT modifying the "getSum(x,y);" in line 6 while using the return method???
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
getSum(x,y);
}
public static int getSum(int x, int y){
int sum = x+y;
return (sum);
}
}
Thank you all in advance!!! I'm still in the beginning stage of coding so I appreciate all the help.
Sorry I thought that you are not allowed to modify getSum method. Just add System.out.println(sum); to getSum method.
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y){
//no need to create temprory varibale
return x+y;
}
}
Just print it inside the getSum method, before returning:
public static int getSum(int x, int y){
int sum = x+y;
System.out.println(sum);
return sum;
}
As mentioned by #Stultuske in the comments. if you want to only print the sum, and never get it. Then just remove the return type and aswell name the method differently for clarification:
public static void printSum(int x, int y){
System.out.println(x + y);
}
You might even want to introduce a whole new method. Leaving the old getSum all on itself. The new method then delegates and just prints the result returned:
public static void printSum(int x, int y){
System.out.println(getSum(x, y));
}
Actually, you are compiling a program without any output. You have to use something like
System.out.println(getSum(x, y));
Otherwise you wont get any output.
If you modify the main-method like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println(sum);
}
you will get the output: 52.
In this case you will save the returned Integer in sum and will print a new line to your console.
If you want to add some words, you can modify the main like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println("The result is" + sum);
}
You should store your result in a variable or display a result.
int c = getSum(x,y);
or
System.out.println("The result of the two numbers are " +getSum(x,y);
Try This:
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y)
{
int sum = x+y;
return (sum);
}
}
This code will resolve your problem very easily.

How to call on a method in Java

import java.util.Scanner;
public class Question1
{
public static void main(String[] args)
{
Primary test = new Primary();
test.Main();
}
}
class Primary
{
double x;
double y;
double z;
double Small;
double Avg;
int dad;
final int userNumbers = 3;
Scanner in = new Scanner(System.in);
public void Main()
{
System.out.println("Please enter 3 numbers");
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
Primary test = new Primary();
test.Smallest();
test.Average();
System.out.println("The average of the numbers is:" + Avg);
System.out.println("The smallest of the numbers is:" + Small);
}
public void Smallest()
{
if(z < y && z < x)
Small = z;
if (x < z && x < y)
Small = x;
if (y < z && y < x)
Small = y;
}
public void Average()
{
Avg = x + y + z / userNumbers;
}
}
I have no clue what to do since everything ive tried either gives me an error or I'm just not doing it right. I'm not even sure I'm doing what the professor is asking me to do, and he never responds to his emails. If anyone could help me it would be greatly appreciated (And if I'm not doing what my professor is asking please let me know).
Heres his instructions + The assignment on page 248
Around Page 248. Practice Exercise E5.1.You will create one class that has three methods: main(), smallest(), and average(). main() reads the test data values and prints the results. You may want to do this in a loop. smallest() and average() do not read data values or print the results. The main() method reads the data values and prints the results.
Write the following methods and provide a program to test them.
a. double smallest(double x, double y, double z), returning the smallest of the arguments
b. double average(double x, double y, double z), returning the average of the arguments
Here try this....`
let me know how that works
import java.util.ArrayList;
import java.util.Scanner;
package javaapplication17;
public class Question1 {
public static void main(String[] args)
{
double avg, small;
Scanner in = new Scanner(System.in);
System.out.println("Please enter 3 numbers");
double x = in.nextInt();
double y = in.nextInt();
double z = in.nextInt();
//Method calls -----------------------------------
avg = average(x, y, z);
small = smallest(x, y, z);
//Method calls -----------------------------------
System.out.println("The average of the numbers is: " + avg);
System.out.println("The smallest of the numbers is: " + small);
}
public static double smallest(double x, double y, double z)
{
double small = 0;
if(z <= y && z <= x)
small = z;
if (x <= z && x <= y)
small = x;
if (y <= z && y <= x)
small = y;
return small;
}
public static double average(double x, double y, double z)
{
return (x + y + z) / 3.0;
}
}
You do need to learn java to do this. See https://en.wikiversity.org/wiki/Java_Tutorial/Hello_World! and others like it for hints.
To answer the question given to you, you only need one class - you have two. In that class, you need three methods. Two of the methods return values - you have them returning a void. You shouldn't need any field variables in your class.
Structure the class as in the tutorial link. (This isnt' a working answer - you still have to do the homework.)
public class Question1 {
public static void main( String[] args ) {
double x, y, z;
// Add your a loop here to collect your x, y and z
// data and process it
while (true) {
// Collect the data ...
// Call the methods
double smallest = smallest(x, y, z);
double average = average(x, y, z);
// Do something with the results
}
}
public static double smallest(double x, double y, double z) {
double smallValue;
// Add your logic and set smallValue
return smallValue;
}
public static double average(double x, double y, double z) {
// Calculate the average and return that value
// as in the smallest method...
}
}
To test the functions, write another program like the following:
import Question1;
public class TestQuestion1 {
public static void main( String[] args ) {
// Add test code here. Something like
double result = Question1.smallest(1.0, 2.0, 3.0)
// Check that the result is 1.0
// Add other tests - output the results
}

Method to sum 2 numbers and return the value

So i'm currently trying to finish off my java corse in school but i'm having problem understanding one of the tasks.
The task in question is: Create a method that sums two numbers and returns the sum. The methodhead should look like this; public static double sum(double nr1, double nr2)
and the problem i'm running in to is that i simply do not understand how to solve the task.
The only way of solving this task is with this code.
import java.util.Scanner;
class AddNumbers {
public static void main(String args[]) {
int x, y, z;
System.out.println("Enter two integers to calculate their sum ");
Scanner in = new Scanner(System.in);
x = in.nextInt();
y = in.nextInt();
z = x + y;
System.out.println("Sum of entered integers = "+z);
}
}
But with this solution i'm not solving the task like
This may help you
import java.util.Scanner;
class AddNumbers
{
public static void main(String args[])
{
double x, y, z;
System.out.println("Enter two numbers to calculate their sum ");
Scanner in = new Scanner(System.in);
x = in.nextDouble();
y = in.nextDouble();
z = sum(x,y);
System.out.println("Sum of entered numbers = "+z);
}
public static double sum(double nbr1,double nbr2){
return (nbr1+nbr2);
}
}

Java Program - Write a program that calculates the area of a circle using a method called circleArea

This is the code that I came up with so far:
package circlearea2;
import java.util.Scanner;
public class CircleArea2
{
public static void main(String[] args)
{
double a;
double c;
System.out.println("Enter the radius: ");
Scanner scan = new Scanner(System.in);
a = scan.nextDouble();
c = areaCalc(a);
System.out.println("Circle Area is: " + c);
}
public static double areaCalc(double n1) {
double min;
min = (n1 * n1 * 3.14);
return min;
}
}
The problem is fixed. Thanks everyone! I really appreciate your help.
The parameter of areaCalc() should be of type double, but it is int. When you pass a double, it must be converted to an int, but that will cause a loss of precision and the language requires you to make an explicit cast if you attempt that.
If you code your method like this:
public static double areaCalc(double n1) { ... }
You'll have no problem (and it will make more sense too).
The problem is that areaCalc takes an int, but you're providing a double. Change it to take a double:
public static double areaCalc(double n) {
return n * n * 3.14;
}
For more accuracy, you can use Math.PI.
public static double areaCalc(double n) {
return n * n * Math.PI;
}

How to work with an 'x' variable like in math?

How can I work with an 'x' variable like in math?
I need to write a code that determines a polynomial function. For example if the input data is 2, 4, 8, 9 then the function would be 2 + 4x + 8x^2 + 9x^3.
Now I do know how to process the input data etc. but I don't know how to declare a variable that has no value, for example I declared a variable x = double, but I still have to initialize it but I don't want to give x a value at this point yet?
So how can I write a method that for example returns 'x' to the power of something?
This is what I have at the moment (it still doesn't work of course)
public class Interpol {
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
//get user input (polynomial coefficients and interval values x1 and x2)
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
int amountCoefficients = 0;
while (scanner.hasNextDouble()) {
polynomialCoefficients.add(scanner.nextDouble());
amountCoefficients++;
}
String in = scanner.next();
double x1 = scanner.nextDouble();
double x2 = scanner.nextDouble();
//call method f to determine the polynomial function
double x;
double[] termsFunction = new double[amountCoefficients];
for (int i = 0; i < polynomialCoefficients.size(); i++) {
termsFunction[i] = f(i, polynomialCoefficients.get(i));
}
//call method findaroot to determine the root
//print result
}
//determine function of which a root is to be found
public static double f(int i, double polynomialCoefficient) {
if (i == 0) {
return polynomialCoefficient;
}
double x;
return polynomialCoefficient * (Math.pow(x, i));
}
/* //rounds off d to 3 decimals
public static double rnd(double d) {
}
//returns a root in this interval, recursive function
public static double findaroot{double x1, double x2) {
}*/
}
You need to make a Class of objects that represent polynomials. The class will store the coefficients in an instance variable, and provide a method to evaluate the polynomial at a given value.
import java.util.*;
public class Foo {
public static void main(String[] args)
throws Exception
{
Scanner scanner = new Scanner(System.in);
//get user input (polynomial coefficients and interval values x1 and x2)
ArrayList<Double> polynomialCoefficients = new ArrayList<Double>();
int amountCoefficients = 0;
while (scanner.hasNextDouble()) {
polynomialCoefficients.add(scanner.nextDouble());
amountCoefficients++;
}
Polynomial polynomial = new Polynomial(polynomialCoefficients);
String in = scanner.next();
while (scanner.hasNextDouble()) {
double x = scanner.nextDouble();
System.out.println("f(" + x + ") = " + polynomial.evaluate(x));
}
}
static class Polynomial {
ArrayList<Double> _coefficients;
public Polynomial(ArrayList<Double> coefficients) {
_coefficients = coefficients;
}
public double evaluate(double x) {
double result = 0;
// This algorithm is called Horner’s rule. See Knuth.
for (int i = _coefficients.size() - 1; i>= 0; i--) {
result *= x;
result += _coefficients.get(i);
}
return result;
}
}
}
If I run this program and type 2 4 8 9 x 2.7, then it prints f(2.7) = 248.267, which is correct according to Wolfram Alpha.

Categories

Resources