Java - multiplication of variables through parameters - java

what is the best method of calculating the product of integer variables through method parameters? I have tried using mathematical symbols such as '*' to get a result but nothing has been successful and I am lost for answers. Any advice would be greatly appreciated, thanks in advance.
int productOfThreeNumbers(int number1, int number2, int number3){
productOfThreeNumbers(number1 * number2 * number3);
return 0;
}

If you wish to obtain an integer value from a multiplication of integers you could try
public Integer mult(int a,int b){
int c = a*b;
return c;
}
If you want to obtain a double value you could use:
public double mult(int a,int b){
double n1 = (double) a;
double n2 = (double) b;
double c = n1*n2;
return c;
}
you call the method with:
int a = 1;
int b = 2;
int c = mult(a,b);
or
int a = 1;
int b = 2;
double c = mult(a,b);
depending on which method you are using.
But looking at your code just do:
int productOfThreeNumbers(int number1, int number2, int number3){
return (number1 * number2 * number3);
}

Define TriFunction
#FunctionalInterface
interface TriFunction<A,B,C,R> {
R apply(A a, B b, C c);
}
Then, use it:
public class Main {
public static void main(String[] args) {
TriFunction<Integer, Integer, Integer, Integer> triMult = (x,y,z) -> x*y*z;
System.out.println(triMult.apply(2, 1, 3));
}
}

Related

Finding the max of an int and a double?

How do I obtain the max value of both the given int and double values?
package _pasted_code_;
import java.util.Scanner;
public class extra {
public static void main(String[] args) {
double x = 2.0;
double y = 3.0;
double z = 5.67;
int a = 3;
int b = 9;
double answer = max(x, y);
System.out.println("The largest number is: " + answer);
double answer = max(x, y, z);
int max = max(a, b);
}
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static int max (int x, int y) {
if (x > y)
return x;
else
return y;
}
public static double max(double num1, double num2, double num3) {
if ((num1 > num2) && (num1 > num3))
return num1;
else
return num2;
else
return num3;
}
}
You can use Math.max(double a, double b)
and Math.max(int a, int b)
Example:
public static int max(int x, int y) {
return Math.max(x, y);
}
public static double max(double num1, double num2) {
return Math.max(num1, num2);
}
public static double max(double num1, double num2, double num3) {
return Math.max(Math.max(num1, num2), num3);
}
Java will convert an int to a double when needed. Also, just use Java's Math.max().
Like previously stated, you could use the Math.max method inside your code to receive the max number. same with the Math.min(x,y). They both work the same way.
therefore lets put it in simple terms.
public static double max(double num1, double num2)
{
return Math.Max(num1, num2);
}
also
public static int max (int x, int y)
{
return Math.max(x,y);
}
It's quite simple. I believe someone might've answered it already, but it's the same concept.
The best practice here is to use method overloading (Assuming that you do not want to use Java's own max/min method). Any method has its own signature and they are uniquely identified with the signatures. So, what I would recommend is defining method as follows:
public static int max(int x, int y) {
// your implementation
}
public static double max(double x, double y) {
// your implementation
}
But remember, it is always better to use Java's min, max methods.
First off, if you just use parameters of type double, Java will automatically perform a primitive conversion from int to double.
Second, you can indeed use Math.max of compare the two, returning the highest value.
However, if you have many doubles to compare, it will become cumbersome to write Math.max for each comparison. In that case, I suggest using a stream:
double[] numbers = ...;
double max = Arrays.stream(numbers)
.max()
.get();
Note: this will throw an Exception if the array is empty.

While building an object for rational number

public class Rational {
int num, denom; /*I'm building an object named "Rational, which takes in two int values, num and denom, and represent them as a rational number(num/denom)*/
public Rational(int a, int b){//this is the constructor
this.num = a;
this.denom = b;
}
public Rational(){//this is just another form of constructor
this.num = 0;
this.denum = 0;
}
public static void printRational(Rational x){/*this is the method that prints the rational number in a fractional format*/
System.out.println(x.num+"/"+x.denom);
}
public static int gcd(int a, int b){/*this is the method which finds the greatest common denominator of numerator of denominator. This will be used to simplify the fraction*/
if(b == 0){
return a;
}
else{
return gcd(b, a%b);
}
}
public static Rational add(Rational x, Rational y){/*this is a method which adds the two rational numbers(or objects) together, then simplify it utilizing the gcd method*/
Rational z = new Rational();
z.denom = (x.denom * y.denom);
z.num = y.num*x.denom + x.num*y.denom;
z.denom = z.denom/gcd(z.num, z.denom);
z.num = z.num/gcd(z.num, z.denom);
return z;
}
public static void main(String[] args) {
Rational y = new Rational(1, 2); //1st Rational Object: y
Rational z = new Rational(2, 6); //2nd Rational Object: z
printRational(add(y, z)); //implementing the method
//result? so far so good. I get the correct result
}
}
The problem I'm facing is I don't understand is that why this won't work instead and give me an error.
public static Rational add(Rational x, Rational y){
Rational z = new Rational();
int a = (x.denom * y.denom);
int b = y.num*x.denom + x.num*y.denom;
z.denom = a/gcd(z.num, z.denom);
z.num = b/gcd(z.num, z.denom);
return z;
}
Why would this give me an error message: "Exception in thread "main" java.lang.ArithmeticException: / by zero
at Rational.add(Rational.java:47)
at Rational.main(Rational.java:58)" when the instances of the object are int types and I'm temporarility storing the value into int a, b; Help me please if you see something I don't see!! Thank you.
I do not know what is the exact problem, when you say "It is not working". It would have been helpful if you could tell what error is it giving. However, from what you have said, Could it be because you have not initialized z.num and z.denom and are sending them to gcd() ?? They will both be zero, as they are primitive data type "int" so your gcd method will return 0 and cause an exception.
public static Rational add(Rational x, Rational y){
Rational z = new Rational();
int a = (x.denom * y.denom);
int b = y.num*x.denom + x.num*y.denom;
z.denom = a/gcd(z.num, z.denom); <--------------
z.num = b/gcd(z.num, z.denom); <--------------
return z;
}
You are using the wrong implementation for dividing with gcd as the number changes in this case.
z.denom = z.denom/gcd(z.num, z.denom);
z.num = z.num/gcd(z.num, z.denom);//z.denom is changed here.
The z.denom can be 0 as it is changed so gcd is 0 and hence the exception.
So what you can do is.
int gcd = gcd(z.num, z.denom);
z.denom /= gcd;
z.num /= gcd;
Also this fails when either of num or denom is a 0.

Why isn't my quad. equation class working?

My returning values are not coming up as right, and I'm just wondering what I am doing wrong, my code looks fine?!
some of the test that are coming up are:
Test failed: expected was not equal to actual
Expected = 9.000000 and actual = 0.000000
The discriminant is not being computed correctly
Test failed: expected was not equal to actual
Expected = -3.000000 and actual = 0.000000
public class QuadraticEquation {
//coefficients
private double a;
private double b;
private double c;
// created a discriminant instance variable so it's easier to access
// rather than tying out "Math.pow(b, 2) - 4 * a * c" every time
// the discriminant is required
private double discriminant = Math.pow(b, 2) - (4 * a * c);
//constructor
public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
//getter for A
public double getA() {
return a;
}
//getter for B
public double getB() {
return b;
}
//getter for C
public double getC() {
return c;
}
// get discriminant
// the discriminant is inside of the square root,
// and b^2 - 4ac is the expression for the discriminant
public double getDiscriminant() {
//b^2 - 4ac
return discriminant;
}
//get root0
public double getRoot0(){
if (discriminant > 0) {
return -b + Math.sqrt(discriminant) / 2*a;
}
return Double.NaN;
}
public double getRoot1() {
if (discriminant > 0) {
return -b - Math.sqrt(discriminant) / 2*a;
}
return Double.NaN;
}
}
You're trying to calculate the discriminant before you've set a, b and c, so naturally it's coming out zero.
Move the line that calculates the discriminant down into the constructor.
public class QuadraticEquation {
//coefficients
private double a;
private double b;
private double c;
private double discriminant;
//constructor
public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
discriminant = b * b - (4 * a * c);
}
// etc.
Note also that b * b generally outperforms Math.pow(b, 2) because of the way the latter is calculated.
Also, the operations inside getRoot0 and getRoot1 are happening in the wrong order. You need parentheses to do something like this.
public double getRoot0(){
if (discriminant > 0) {
return ( -b + Math.sqrt(discriminant)) / (2 * a);
}
return Double.NaN;
}
and similarly in getRoot1.

Getting NaN when I am trying to compute the zeros of a quadratic formula

I have two classes, the quadratic class and the runner class. This is the quadratic class.
public class Quadratic {
double a;
double b;
double c;
public double discrim = (Math.pow(b, 2) - 4*a*c);
public boolean hasSolutions() {
if(discrim >= 0){
return true;
}
else {
return false;
}
}
public double getSolution1() {
double pos = (b*-1 + Math.sqrt(discrim))/(2*a);
return pos;
}
public double getSolution2() {
double neg = (b*-1 - Math.sqrt(discrim))/(2*a);
return neg;
}
public Quadratic(double a, double b, double c) {}
}
And here is the runner class.
public class QuadraticRunner
{
public static void main( String args [])
{
Quadratic test1 = new Quadratic (1, 5, 6);
Quadratic test2 = new Quadratic (1, -4, 4);
Quadratic test3 = new Quadratic (1, 0, 3);
String equation1 = test1.toString();
boolean hasSolution1 = test1.hasSolutions();
double solution1 = test1.getSolution1();
double solution1b = test1.getSolution2();
String equation2 = test2.toString();
boolean hasSolution2 = test2.hasSolutions();
double solution2 = test2.getSolution1();
double solution2b = test2.getSolution2();
String equation3 = test3.toString();
boolean hasSolution3 = test3.hasSolutions();
double solution3 = test3.getSolution1();
double solution3b = test3.getSolution2();
System.out.println(equation1);
System.out.println(hasSolution1);
System.out.println(solution1);
System.out.println(solution1b);
System.out.println("Expected solutions: -2.0, -3.0");
System.out.println();
System.out.println(equation2);
System.out.println(hasSolution2);
System.out.println(solution2);
System.out.println(solution2b);
System.out.println("Expected solution: 2.0");
System.out.println();
System.out.println(equation3);
System.out.println(hasSolution3);
System.out.println(solution3);
System.out.println(solution3b);
System.out.println("NaN");
}
}
When I attempt to run this, the hasSolutions() method works fine, but both getSolution1() and getSolution2() come out as NaN. If the discriminant were negative I would understand, but it isn't negative for all the tests, so I am not sure where I went wrong.
You are calculating the discriminant before any values are assigned to a, b, or c. Also, you aren't using the constructor values passed in.
double a;
double b;
double c;
public double discrim = (Math.pow(b, 2) - 4*a*c);
public Quadratic(double a, double b, double c) {}
Because of this, you are dividing 0 by 0 in getSolution1 and getSolution2, which in floating-point arithmetic yields a NaN. (In math it's undefined.)
Move that calculation inside the constructor, after you assign values to a, b, and c.
public double discrim;
public Quadratic(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
discrim = (Math.pow(b, 2) - 4*a*c);
}
Your constructor doesn't set the field values, so a has a default value of 0 and you divide by zero when you say /(2 * a). Fix your constructor like,
public double discrim; // = (Math.pow(b, 2) - 4*a*c);
public Quadratic(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
this.discrim = (Math.pow(b, 2) - 4*a*c); // <-- also, move the math here.
}

Subclass constructor

The outcome of this code should be "huugiin zardal: 3", but it doesn't work.
Please help. And also is there any easy way to write it?
class Cost3{
int a;
int u;
int x;
Cost3(int a,int u,int x){
}
}
class FC1 extends Cost3{
FC1(int a1, int u1, int x1){
super(a1,u1,x1);
a=a1;
u=u1;
x=x1;
}
public int huugiin_zardal(){
return(((a+u)/2)*(x/100));
}
}
public class Cost2{
public static void main(String args[]){
FC1 h_z=new FC1(3,4,20);
System.out.println("huugiin zardal: "+h_z.huugiin_zardal());
}
}
Your problem is that ((3 + 4) / 2 ) * (20 / 100) is not 3. It is 0 because (20 / 100) is zero ... in integer arithmetic.
Indeed, even ((3 + 4) / 2 ) * 20 / 100 is 60 / 100 which is also 0. So I suspect that your root problem is that you have completely the wrong formula.
In addition, the initialization of a, u, and x should probably be in the supertype constructor not the subtype constructor. (This doesn't fix your current problem, but the way that you have the code at the moment, creating an instance of Cost3 will return an object in which the fields have not been initialized.)
((3+4)/2)*(20/100)
(7/2) * (0)
0
7/2 = 3 not 3.5 since it is truncated in integer division.
the same for 20/100 = 0 not 0.2
Indent your code better too,it helps a lot.
This is a nicer and simpler version of your code, however it will print out 0, for the integer division reasons already discussed by others:
class Cost3 {
int a;
int u;
int x;
public Cost3(int a, int u, int x) {
this.a = a;
this.u = u;
this.x = x;
}
}
class FC1 extends Cost3 {
public FC1(int a, int u, int x) {
super(a, u, x);
}
public int huugiin_zardal(){
return (((a + u) / 2) * (x / 100));
}
}
public class Cost2 {
public static void main(String args[]){
FC1 h_z = new FC1(3, 4, 20);
System.out.println("huugiin zardal: " + h_z.huugiin_zardal());
}
}
Notice that if the superclass handles the instance variables (a, u, and x), then there is no need to set them in the subclass, you just invoke the correct constructor via super().
It is hard to know exactly what your intention is, but one guess is that you want a base class (Cost3) that can handle particular variables, and have extensions (e.g. FC1) that return values based on different calculations. If so, it would be more logical to provide the base class as abstract, as follows:
class abstract Cost3 {
int a;
int u;
int x;
public Cost3(int a, int u, int x) {
this.a = a;
this.u = u;
this.x = x;
}
public abstract int calculate();
}
class FC1 extends Cost3 {
public FC1(int a, int u, int x) {
super(a, u, x);
}
public int calculate() {
return (((a + u) / 2) * (x / 100));
}
}
In your huugiin_zardal() method, all your variables are declared as int. So the division operator is performing integer division, which will silently truncate any remainder. For integer division, 20 / 100 = 0.
Just cast one of your variables to double and it will promote the entire expression to be evaluated as floating-point, only rounding to integer at the end.
How are you getting 3, and what exactly are you trying to achieve, your question is not very clear?
As for the code it will execute the following with the parameters you provided.
(((3+4)/2)*(20/100))
((7/2)*(0) // 10/100 will give you 0 unless you cast this calculation
3*0 //7/2 gets set to 3 since this is an int calculation
final answer 0.
Depending on what you are trying to achieve, you may just need to use something other than int calculations.

Categories