Finding the max of an int and a double? - java

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.

Related

double cannot be converted to Calculator incompatible types

I just made this account, and I also just started programming java a few days ago just out of interest. I've been having an extremely hard time writing a Calculator program using objects and methods instead of if/then statements.
import java.util.*;
public class Calculator {
double x;
double y;
double result;
public Calculator(double a, double b) {
x = a;
y = b;
}
public double Add(double numOne, double numTwo) {
x = numOne;
y = numTwo;
result = x + y;
return result;
}
public double Subtract(double numOne, double numTwo) {
x = numOne;
y = numTwo;
result = x - y;
return result;
}
public double Multiply(double numOne, double numTwo) {
x = numOne;
y = numTwo;
result = x * y;
return result;
}
public double Divide(double numOne, double numTwo) {
x = numOne;
y = numTwo;
result = x / y;
return result;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("First number: ");
Double firstNum = input.nextDouble();
input.nextLine();
System.out.println("Operator: ");
String operator = input.nextLine();
System.out.println("Last number: ");
Double secNum = input.nextDouble();
if(operator == "+") {
Calculator ans = new Calculator(firstNum, secNum);
ans = ans.Add(firstNum, secNum);
}
}
}
I cannot figure out how to work around how this code uses doubles, as when calling the class I get "double cannot be converted" when I'm not trying to convert any doubles besides the ones declared in the class. I know this isn't a conventional way of making a calculator I just wanted to improve my knowledge of methods and classes. Thanks!
The error is on line 59, error: incompatible types: double cannot be converted to Calculator
You are trying to assing double to Calculator instance, which is not possible.
See last line:
ans = ans.Add(firstNum, secNum);.
Method Add returns double and you are trying to assing it to Calculator reference.
What you can do:
Assing returned double to double reference.
double result = ans.Add(firstNum, secNum);
Also, you don't need to copy the parameters in your methods :
public double Add(double numOne, double numTwo) {
x = numOne;
y = numTwo;
result = x + y;
return result;
}
Could be simplified to :
public double Add(double numOne, double numTwo) {
return numOne + numTwo;
}
Because you don't use the fields x and y later in your class.

Java - multiplication of variables through parameters

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

Function only calls the same block with different input

import java.io.*;
public class LargestOfTwo{
public static void main(String args[]) throws Exception{
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
double num1, num2 , large;
System.out.println("Enter two numbers, and I will show you which one's largest!\n");
System.out.println("Enter two numbers: ");
num1 = Double.parseDouble(scan.readLine());
num2 = Double.parseDouble(scan.readLine());
large = largest(num1,num2);
System.out.print("Largest of the numbers is "+large);
}
private static double largest(int x,double y){
System.out.println("id");
if (x>y)
return x;
else
return y;
}
private static double largest(double x,int y){
System.out.println("ii");
if (x>y)
return x;
else
return y;
}
private static double largest(double x,double y){
System.out.println("dd");
if (x>y)
return x;
else
return y;
}
}
I need to find the largest of 2 inputted numbers, using function overloading(input float values and int values) .
I checked if the call goes to the specific method, by those print texts (id, ii, dd).
private static double largest(int x,double y){
System.out.println("id");
}
private static double largest(double x,int y){
System.out.println("ii");
}
private static double largest(double x,double y){
System.out.println("dd");
}
But it executes the dd only :-
private static double largest(double x,double y)
is it because the wrong variable initialization or not? and how can I fix this ?
Both num1 and num2 are declared as double, so there is really no other outcome to expect other than what you got.
In this line, num1 and num2 is double. So the method which has double parameters is calling.
num1 = Double.parseDouble(scan.readLine());
num2 = Double.parseDouble(scan.readLine());
if you want to call the largest(int x,double y) method, then cast num1 as an integer, i.e. largest((int)num1, num2). if you want to call largest(int x,int y) then cast both num1 and num2 as integers

converting an if statement to a conditional operator in Java

How do I simplify this code with a conditional operator in Java?
This is from dr. Liang's Introduction to Java.
public class Test {
public static void main(String[] args) {
int i = 3;
int j = 4;
int k = max(i, j);
System.out.println("The max int is " + k);
}
public static int max(int num1, int num2) {
int result;
if (num1 > num2) {
result = num1;
}
else {
result = num2;
}
return result;
}
}
You can turn things into a one-liner using the conditinal ternary operator:
return (num1 > num2) ? num1 : num2;
But just for the record: it would be better to keep that max method around; simply for the sake of readability. It helps to have that functionality in its own method.
But of course: you want to read about java.lang.Math.max() which already provides exactly that functionality (not only for int, but all the other numerical primitive types as well)!
So, the real answer is: yes, use a method for that check; but don't create your own version; use the one that is already coming with Java by default. In other words: do not re-invent the wheel. Even when it is just a small wheel like this one.
While you could use the conditional operator ? : to implement this
public static int max(int num1, int num2) {
return num1 > num2 ? num1 : num2;
}
But, I would prefer Math.max(int, int) like
public static int max(int num1, int num2) {
return Math.max(num1, num2);
}
You might also choose to use varargs and support an arbitrary number of int(s). Using an IntStream you could do
public static int max(int... nums) {
return IntStream.of(nums).max().getAsInt();
}
You can use a conditional ternary operator.
int k = (i > j) ? i : j;
This expression evaluates to:
If i is greather than j, assign i to k. If not, assign j to k.
This would be one way to modify your example to use the ternary operator.
You should generally keep the values in the operator short otherwise they get hard to read.
public class Test {
public static void main(String[] args) {
int i = 3;
int j = 4;
int k = max(i, j);
System.out.println("The max int is " + k);
}
public static int max(int num1, int num2) {
int result;
result = (num1 > num2) ? num1 : num2;
return result;
}
}

How do I extend the program to then declare the smallest number?

Can I extend the program’s functionality to additionally tell the user the smallest number, by creating a separate method, smaller, in a similar fashion to the larger method?
public static void main(String[] args)
{
System.out.println("Please enter two numbers");
Scanner scan = new Scanner(System.in);
int first = scan.nextInt();
int second = scan.nextInt();
System.out.println("The largest "+larger(first, second));
}// end of main
public static double larger(double x, double y)
{
if (x >= y)
return x;
return y;
} //end of larger
This is trivial, e.g. (keeping the same code conventions)
public static double smaller(double x, double y)
{
if (x >= y)
return y;
return x;
} //end of larger
The above is not optimal, but it aligns with the existing code.
You can also use Math.min(double a, double b), or ternary operator: a < b ? a : b.
P.S. One number is not greater than another if they are equal.

Categories