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
Related
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.
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.
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));
}
}
I try to assign bit wise operators into variables. How can i do it?
Eg
String bitOp="";
String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE);
if(rFunction.toUpperCase()=="AND")
bitOp="&";
if(rFunction.toUpperCase()=="OR")
bitOp="|";
if(rFunction.toUpperCase()=="XOR")
bitOp="^";
int res= x +bitOp+ y; // if the operator is "AND" , this should be x & y.
//Here NumberFormatException error shows.
System.out.print(res);
But it doesn't work. Anyone please!!!
You could make your own BitOperator:
public enum BitOperator {
AND {
#Override
public int calc(int x, int y) {
return x & y;
}
},
OR {
#Override
public int calc(int x, int y) {
return x | y;
}
},
XOR {
#Override
public int calc(int x, int y) {
return x ^ y;
}
};
public abstract int calc(int x,int y);
}
Usage(add some Exception handling):
String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE);
System.out.println(BitOperator.valueOf(rFunction.toUpperCase()).calc(x, y));
Your code shouldn't even compile so I am not sure of what you really want to achieve. Do you want to evaluate the String expression you create or do you just want to get the result more classically? Where do x and y come from...? There is an important part of your code that is missing.
Anyway I would chose the second option:
int eval;
String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE).toUpperCase();
if(rFunction.equals("AND")){
eval = x & y;
} else if(rFunction.equals("OR")){
eval = x | y;
} else if(rFunction.equals("XOR")){
eval = x ^ y;
} else {
//here you could also throw an exception
//or loop and request the user to renew their choice
System.out.print("Invalid choice");
return;
}
System.out.print(res);
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.