Can't cast Integer into Double (Wrapper class) - java

I tried to create a function which return a random int between x and y if x and y are integer but if x or y is a double the function return a double between x and y. But when I try with a integer it throw an Exception:
"class java.lang.Integer cannot be cast to class java.lang.Double (java.lang.Integer and java.lang.Double are in module java.base of loader 'bootstrap')"
how can I fix it?
public class Test {
public static void main(String[] args) {
System.out.print(rand(10,12.0));
}
public static<t extends Number> double rand(t x,t y) {
double a = (double) x;
double b = (double) y;
b = a < b ?(a + (b - a) * Math.random()):(b + (a - b) * Math.random());
return (x instanceof Double || y instanceof Double) ? b : (int) b;
}
}

The problem is that you are working with reference types (wrapper classes) instead of primitive types. A cast from int to double works, but a cast from Integer to Double doesn't. So you will need to find some other way to convert this.
Since you define t extends Number, you can use any method of Number for x and y.
So instead of casting to double, use this:
public static<t extends Number> double rand(t x,t y) {
double a = x.doubleValue();
double b = y.doubleValue();

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.

Coding the Pythagoras theorem

Hi I am a beginner at java and I'm trying to write code to solve the Pythagoras' theorem. Here's what I've done so far however I keep getting errors with an illegal starter on line 14 as well as a "class, interface, or enum expected" error on line 31.
public class Pythagoras{
public static void main(String[] args){
double a1 = 5.2;
float a = (float)a1;
double b1 = 8.4;
float b = (float)b1;
double c1 = 0;
float c = (float)c1;
float resultC = (float)method (c);
System.out.println(resultC);
public static float method(float c){
if (c = 0){
float result = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
return result;
}
if (b = 0){
float result = Math.sqrt(Math.pow(c, 2) - Math.pow(a, 2));
return result;
}
if (a = 0){
float result = Math.sqrt(Math.pow(c, 2) - Math.pow(b, 2));
return result;
}
}
}
}
In java you cannot have a method defined inside another method. You would have to pull the method public static float method(float) out of main.
There are other flaws, for example:
Here: if (c = 0) you're assigning the value.
method has return statements inside ifs, but what if none is hit? Nothing is returned.
(float)method (c) you're casting to float something that is defined to be float.
Instead of double a1 = 5.2; float a = (float)a1; why don't you write float a = 5.2f?

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

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.

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