Write Method provide Program - java

I am a beginner at java and for my class we are learning about methods. For my first program I have to write a method and provide a program for: double average(double x, double y, double z) returning the average of the arguments. Here is my program so far
//**METHOD**//
Scanner in = new Scanner(System.in);
System.out.println("Enter variable x");
double x = in.nextDouble();
System.out.println("Enter variable y");
double y = in.nextDouble();
System.out.println("Enter variable z");
double z = in.nextDouble();
double average;
System.out.println("The average is: " + average);
//TEST PROGRAM//
public static double average(double x, double y, double z)
{
double average = (x * y * z)/3;
return average;
}

A method is only useful if you use it. You will want to reference (or call) the method where you want to use it.
In your code:
System.out.println("The average is: " + average(x, y, z) );
And to clarify, the average is the sum of all values divided by the number of values.
In this case it would be (x + y + z) / 3 not (x * y * z) /3

double average = (x * y * z)/3;
// ^ ^ what?
Here's your first problem. Why are you multiplying?
double average;
System.out.println("The average is: " + average);
Your second problem is that you didn't actually call the method. If you just define a method and don't call it, Java doesn't know when you want it called or what arguments you want to use. Defining a variable with the same name doesn't implicitly call the method or anything like that. The method won't run at all. Call it with the arguments you want to get a value:
System.out.println("The average is: " + average(x, y, z));

You also need your code to exist within a class and it will need a public static void main(final String[] args) {} method in order to run.

Call the method like this:
double average = average(x, y, z);
System.out.println("The average is: " + average);
And for the record, the average is the sum of the terms divided by the number of terms, not the product. So change your average method to this:
public static double average(double x, double y, double z)
{
double average = (x + y + z) / 3;
return average;
}

Related

Is there a way that I can cast the variables in my Java program so that I get a double output?

I am a beginner in Java and I am being asked to write a program to find the average of three grades. I am trying to figure out how to get a double output by type casting but I don't know where to cast. I have already written some code myself but the grader is still saying I'm not getting the right answer.
Here are the program instructions:
In the code below, type in three made up int grades and then sum and
average them. Use casting to report the result as a double. For
example, if the grades are 90, 100, and 94, the sum of the three
numbers is 90 + 100 + 94 = 284, and the average is the sum 284 divided
by 3 which casted to a double is 94.666667. You should use your
variables instead of the numbers in your formulas. Follow the
pseudocode below.
Type in three made up int grades and then sum and average them. Use
type casting to report the result as a double.
Here is my code:
public class Challenge1_6
{
public static void main(String[] args)
{
// 1. Declare 3 int variables called grade1, grade2, grade3
// and initialize them to 3 values
int grade1 = 78;
int grade2 = 95;
int grade3 = 84;
// 2. Declare an int variable called sum for the sum of the grades
int sum;
// 3. Declare a variable called average for the average of the grades
int average;
// 4. Write a formula to calculate the sum of the 3 grades (add them up).
sum = grade1 + grade2 + grade3;
// 5. Write a formula to calculate the average of the 3 grades from the sum using division and type casting.
average = sum / 3;
// 6. Print out the average
System.out.println(average);
}
}
This is my output (It wants a decimal but I don't know how to get it):
enter image description here
Well the average variable must be double
and you cast the division result to fit in the average variable
double average;
// 4. Write a formula to calculate the sum of the 3 grades (add them up).
sum = grade1 + grade2 + grade3;
// 5. Write a formula to calculate the average of the 3 grades from the sum using division and type casting.
average = (double) sum / 3;
System.out.println(average);
Simply change the variable "average" to double.
double average=Double.valueOf(sum / 3);
Logic is:
At least one variable in the function (a/b) should be the type of double
Or we need to convert the int value to Double as required.
You can simply divide by the double literal 3.0 or 3d so that it performs floating point division instead of instead divison.
double average;
sum = grade1 + grade2 + grade3;
average = sum / 3.0;
Demo!
Just convert the average to double to avoid any missing due to the cast from double to int
public class Challenge1_6 {
public static void main(String[] args) {
int grade1 = 78;
int grade2 = 95;
int grade3 = 84;
int sum;
double average;
sum = grade1 + grade2 + grade3;
average = sum / 3;
System.out.println(average);
}
}

It should be two errors here but I can´t see them

New error:
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Length in meters: ");
double length = input.nextDouble();
System.out.print("Weight in kilos: ");
double weight = input.nextDouble();
double bmi = weight / length * length;
System.out.printf("BMI");
input.close();
}
}
You're considering variables meter and bmi to be of type double. However, the expression on the right hand side of assignment is divide operation among int which will cause precision loss.
You'll need to cast one of the operands on right hand side to double to preserve precision.
double meter = (double) centimeter / 100;
double bmi = (double) weight / (meter * meter);
In your System.out.printf, you're using the non-existing length variable. As I understand, there should be meter variable there.
I've also fixed a typo in first System.out.print in Length word.
The fixed class looks like this (UPDATE: also fixed the integer division, which was the actual question's target):
import java.util.Scanner;
public class BMICalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Length in centimeter: ");
int centimeter = input.nextInt();
double meter = ((double) centimeter) / 100; // fixed integer division by casting to double
System.out.print("Weight in whole kilo: ");
int weight = input.nextInt();
double bmi = ((double) weight) / (meter * meter); // fixed integer division by casting to double
System.out.printf("BMI for someone who is %.2f meter long, and weight %d kilo is %.1f", meter, weight, bmi);
input.close();
}
}

Sin taylor series recursive approximation

I need some insight on my recursive method of calculating the sin Taylor series, which doesn't work properly. The method calls two other recursive methods which are a recursive pow method and a recursive factorial method. I compared my findings with an iterative sin method giving me the correct solution. What is missing in my recursive sin method ?
Approximation of sin(x)= x - x^3/3! + x^5/5! -x^7/7!+ ...
public class SinApprox
{
public static void main (String [] args)
{
Out.println(sinx(1, 1, 2, 1, 1, 0, 1));
Out.print(sinIT(2));
}
static double sinIT(double x)
{
double sin = 0;
double a = x;
double b = 1;
double term = a/b;
double vz = 1;
double i = 1;
while(term > 0.000001)
{
i = i +2;
sin = sin + (term*vz);
a= rekursivPow(x,i);
b = rekursivN(i);
term = a/b;
vz = -1 * vz;
}
return sin;
}
static double rekursivN(double n)
{
if(n==1)
{
return 1;
}
return n * rekursivN(n-1);
}
static double rekursivPow(double x , double y)
{
if(y == 1)
{
return x ;
}
return x * rekursivPow(x , y - 1);
}
static double sinx(double i ,double n, double x, double y, double vz, double sum, double pow)
{
double term = pow / n;
if(term > 0.000001)
{
sum = sum + (term * vz);
vz = -1 * vz;
i = i +2;
n = rekursivN(i);
y = y +2;
pow = rekursivPow(x ,y);
return sinx(i, n, x , y , vz, sum, pow);
}
return sum;
}
}
Step one would be to write out the function in a way that makes the recursive relationship clear (you can't write code for what isn't clear) so, don't start with this:
sin(x)= x - x^3/3! + x^5/5! -x^7/7!+ ...
But instead, ask "how can I make all those terms with x look the same":
sin(x)= x^1/1! - x^3/3! + x^5/5! + ...
Good start, but if we're recursing, what we're really looking for is something that only computes one of those terms, and then calls itself with updated arguments to compute the next term. Ideally, we want something like:
doThing(args) {
return simpleComputation() + doThings(updatedargs);
}
And then recursion does the rest. So let's first make sure that we only ever have to deal with + instead of a mix of + and -:
sin(x)= (-1)^0 * x^1/1! + (-1)^1 * x^3/3! + (-1)^2 * x^5/5! + ...
And now you have something you can actually express as a recursive relation, because:
sin(x,n) {
return (-1)^n * x^(2n+1) / (2n+1)! + sin(x, n+1);
}
With the "shortcut" function:
sin(x) {
return sin(x,0);
}
And that's where the hints stop, you should be able to implement the rest yourself. As long as you remember to stop the recursion because a Taylor series is infinite, and computer programs and resources are not.

Java: Giving more weight to higher values among inputs

I have some inputs say x1,x2,x3. I have to multiply each input with some weight and add them. Like alpha * x1 + beta * x2 + gamma * x3.
Range of x1,x2,x3 is 0 to 1.
Range of weights is also 0 to 1.
I want some algorithm to give more weight to higher values and less weight to lower values.
Like if x1 has higher value among three then 60% weight age can be given to x1.
x2 has 2nd highest value 30% to it and 20% to last value completing 100%.
What I have tried so far is given below but values are static, I am giving weight 0.6 to highest value the 0.3 and 0.2 respectively. Is there any way to give weight dynamically according to value of input?
if (x1>x2 and x1>x3 ) {
if (x2>x3) {
sum= 0.6*x1 + 0.3*x2 + 0.2*x3;
}
if (x3>x2) {
sum= 0.6*x1 + 0.2*x2 + 0.3*x3;
}
}
if (x2>x3 and x2>x1 ) {
if (x1>x3) {
sum= 0.3*x1 + 0.6*x2 + 0.2*x3;
}
if (x3>x1) {
sum= 0.2*x1 + 0.6*x2 + 0.3*x3;
}
}
if (x3>x2 and x3>x1 ) {
if (x2>x1) {
sum= 0.2*x1 + 0.3*x2 + 0.6*x3;
}
if (x1>x2) {
sum= 0.3*x1 + 0.2*x2 + 0.6*x3;
}
}
You're saying but values are static.
If by that you mean that you hardcoded values like:
double x1 = 1.0;
double x2 = 2.0;
double x3 = 3.0;
then the solution is to get them by user input:
Scanner scanner = new Scanner(System.in);
System.out.print("x1=");
double x1 = scanner.nextDouble();
System.out.print("x2=");
double x2 = scanner.nextDouble();
System.out.print("x3=");
double x3 = scanner.nextDouble();
scanner.close();
Then you make all the calculations.

Creating a java program that given 3 terms as input(a,b,c) in that order prints their roots

Wrie a method printRoots that given 3 terms as input(a,b,c) in that order prints their roots
We have the following given information
If b²-4ac is a positive number, your program should print “The two roots are X and Y” where X is the larger root and Y is the smaller root
If b²-4ac *equals 0*, the program should print. “The equation has one X” where X is the only root
If b²-4ac is a negative number, the program should print.” The equation has two roots(-X1 + Y1i) and (-X2 and Y2i)
The term can be determined based on:
If b^2 - 4ac is a negative number, then the quadratic equation becomes: (-b+/- √C)/2a
-This means the equation can be simplified to become (-b+/- √Ci)/2a where the square root is not a positive number
Calculate the coefficient and print that(i.e X1 is -b/2a and Y1 is sqrt(-C)/2i
Note: Not allowed to use Scanners for this question
Is it possible for someone to review my program and tell me where I have gone wrong and do i just remove my scanners to make it a program without scanners?
import java.util.Scanner;//delete this part after
public class findingRoots {
public static void main(String[] args)
{
}
public static double printRoots (){ //should it be double here or int?
//read in the coefficients a,b,and c
Scanner reader = new Scanner(System.in);
int a=reader.nextInt();
System.out.println("Enter the value of a");
int b=reader.nextInt();
System.out.println("Enter the value of b");
int c=reader.nextInt();
System.out.println("Enter the value of c");
//now compte the discrimintat d
double discrimintant = d;
double X,Y; //root 1 & root 2, respectively
// is the step double X,Y necessary?
double d = (b*b)-(4.0*a*c);
if (d > 0.0){
d = Math.sqrt(d);
System.out.println("The two roots are X and Y");
double X = (-b + d)/(2.0 * a ); //X= root 1, which is larger
double Y = (-b - d)/(2.0 *a); //Y= root 2, which is the smaller root
System.out.println("Root 1" = X "and" "Root 2" "=" Y);
}
else{
if (d==0.0) //then...how to write?
System.out.println("The equation has one root X")//where X is the only root
double X = (-b + 0.0)/(2.0 * a);//repeated root
System.out.println("Root" "=" X);
}
else{
if(d < 0.0)
System.out.println("The equation has two roots (-X1 + Y1i) and (-X2 +Y2i)");
// where i represents the square root of negative 1
double X1 = -b/(2*a);
double Y1 = (Math.sqrt(-C))/(2*a);
double X2 = -b/(2*a);
double Y2 = (-(Math.sqrt(-C)))/(2*a);
double Y2 = (-(Math.sqrt(-C)))/(2*a);
System.out.println("Root 1" "=" (-X1 + Y1i) "and" "Root 2" "=" (-X2 +Y2i)");
}
}
}
you can pass input from command lines. You will get the data at args array
in public static void main(String[] args) here args refers to command line arguements
when you run a java program using
java MyApp arg1 arg2
in your main args[0] is arg1 and args[1] is arg2
So in your case run the app like following command
java findingRoots 1 2 3
and in main
int a= Integer.parseInt(args[0])
N.B I think you would like to validate the command line parameters. check both the args.length and if they are int or not

Categories

Resources