When you convert double to int, the precision of the value is lost. For example, when you convert 4.8657 (double) to int, the int value will be 4. Primitive int does not store decimal numbers, so you will lose 0.8657.
In your case, 0.7 is a double value (floating point treated as double by default unless mentioned as float - 0.7f). When you calculate price*much*0.7, the answer is a double value and so the compiler wouldn't allow you to store it in a type integer since there could be a loss of precision. That's what is "possible lossy conversion", you may lose precision.
So what could you do about it? You need to tell the compiler that you really want to do it. You need to tell it that you know what you are doing. So explicitly convert double to int using the following code:
int total2= (int) (price*much*0.7);
/*(int) tells compiler that you are aware of what you are doing.*/
//also called as type casting
In your case,since you are calculating the cost, I'll suggest you to declare variable total2 as the type double or float.
double total2=price*much*0.7;
float total2=price*much*0.7;
//will work
Answer from Mathews Mathai on Stack OverflowWhen you convert double to int, the precision of the value is lost. For example, when you convert 4.8657 (double) to int, the int value will be 4. Primitive int does not store decimal numbers, so you will lose 0.8657.
In your case, 0.7 is a double value (floating point treated as double by default unless mentioned as float - 0.7f). When you calculate price*much*0.7, the answer is a double value and so the compiler wouldn't allow you to store it in a type integer since there could be a loss of precision. That's what is "possible lossy conversion", you may lose precision.
So what could you do about it? You need to tell the compiler that you really want to do it. You need to tell it that you know what you are doing. So explicitly convert double to int using the following code:
int total2= (int) (price*much*0.7);
/*(int) tells compiler that you are aware of what you are doing.*/
//also called as type casting
In your case,since you are calculating the cost, I'll suggest you to declare variable total2 as the type double or float.
double total2=price*much*0.7;
float total2=price*much*0.7;
//will work
You are trying to assign price* much* 0.7, which is a floating point value (a double), to an integer variable. A double is not an exact integer, so in general an int variable cannot hold a double value.
For instance, suppose the result of your calculation is 12.6. You can't hold 12.6 in an integer variable, but you could cast away the fraction and just store 12.
If you are not worried about the fraction you will lose, cast your number to an int like this:
int total2 = (int) (price* much* 0.7);
Or you could round it to the nearest integer.
int total2 = (int) Math.round(price*much*0.7);
First post, sorry if I make a mistake. Believe I didn't miss any rules.
Code: https://jsfiddle.net/80wLpmj1/
Error: Possible lossy conversion from double to int error. int birthrate = 1.0 / 7.0 ^
It does this for birthrate, deathrate, and immigrationrate. I've changed everything from "int" to "double" and it compiles, but then when executed I get decimals where I don't want them.
If you want to explicitly tell the compiler that you want to convert the numbers to integers, you should cast them as such. Example: int x = (int)(10.0/2.0) will make x have a value of 5.
Do note, however, that in the case of int birthrate, the operation 1.0/7.0 will simply be 0 when cast to an int.
Small hint: jsfiddle is for JavaScript, ideone is for Java. - Not the same language.
You need to review your data types:
-
int and long are for whole numbers only.
-
float and double are for decimal numbers
So, when you write
int birthrate = 1.0/7.0;
Java will complain that it is a lossy conversion because you lose all the decimals and the result will just simply be 0 (because 7 fits in 1 exactly 0 times - integer division - primary school maths).
What you want to store your birthrate in is a double:
double birthrate = 1.0/7.0;
will yield the correct result of 0,142857142857142 (rounded after the 15th digit due to double precision).
I've changed everything from "int" to "double" and it compiles, but then when executed I get decimals where I don't want them.
Which just means that you have to perform a cast to int where you want no decimals.
Do all the math in doubles and finally, when displaying, cast to int.
Videos
Can the Math.round() Function Help in Double To Int Conversion?
Will the Lost Data Be Recoverable After Conversion From Double To Int?
How Will the Number Be Rounded After Typecasting It To Int?
At first I had made the program in Int, but since the division wasn't giving me the correct answer (since I needed a decimal place) I replaced the variables with double. But i'm still getting errors.
https://github.com/Lynlyn2003/Array-Processing/blob/main/CopyOfArrayProcessing2.java
The first problem is a simple typo. Java is case sensitive, so cube and Cube mean different things. Solution: 1) be consistent, and 2) use names starting with lowercase letters for method names ... as per the Java style guides.
The second problem is due to the method signature for Math.pow; see the javadoc. It returns the result as a double. You then attempte to return the double as an int, and that is a lossy conversion.
The solutions include:
return b * b * b; // i.e. don't use `pow`.
or
return (int) Math.pow(b, 3);
The second one directly addresses your compilation error by casting the double return to an int. This is the way you tell the compiler that the lossy conversion is actually OK.
The lossy conversion error message you are seeing refers to that fact for large enough values of b, the result of Math.pow(b, 3) will be too large to be represented as an int1. With the type cast in place, Java will convert a floating point number that is "too large" into Integer.MAX_VALUE.
The first solution is faster and simpler code, but if b is too large, the calculations will silently overflow and you will get a nonsense answer.
UPDATE - If you wanted overflow to always be treated as an error then:
return Math.multiplyExact(b, Math.multiplyExact(b, b));
or
return Math.toIntExact((long) Math.pow(b, 3));
or variations on the above.
1 - Actually, the compiler doesn't know about the semantics of pow, so it doesn't know about "... for large enough values of b ...". But it does know that if the method call did return a large enough value, then the conversion would be lossy. That's why the message says "possible lossy conversion".
Two problems:
- Letter case is important:
Cubeis not the same ascube. - Your function
cube(int)returns an integer, but the output ofMath.powis adouble.
You should probably change cube() to return a double.
Then you have more code to write in the main method to use the results of calling cube.
The message says when you call pattern(t, length); at line 13 you're passing it a double length when it expects an int length. If you change the pattern and triangle methods to take a double length instead of an int length it will fix the error.
Edit to explicitly explain the error
Your methods take an int which can only hold values up to 2^32 - 1. Doubles can hold values up to ~ 1.7*10^308 (See MAX_VALUE constant in Double class for more exact limit). This means that a double can potentially have values (precision) that would be lost if it was used as an int.
Your length parameter in pattern2() is double. However, in pattern(), length is int. Java would not automatically convert from double to int for you.
Your return type of function fallingDistance() should be double.
public static double fallingDistance()
{
double g = 9.8;
int t = 5;
double d = (1/2)*g*t*t;
return(d);
}
The problem with your code is that it is expecting an integer value in return statement but you are return a double which is why it is throwing the error. Go through this link to understand this better.
Does anyone know why I am getting this error even though all the relevant variables are doubles?
/*
This program will roll a pair of dice 10000 times, 11 separate times
to find out the average number of rolls to achieve the desired total
of two dice.
*/
public class Practice {
/*
The main method will iterate all the possible totals then call the
computeRoll function to roll the dice 10000 times. The main method
will then print a table showing the average number of rolls to get
a given total per possible total.
*/
public static void main (String [] args) {
int i;
double averageNumberOfRolls;
double [] averageTable;
averageTable = new double [13];
System.out.println ("This program will roll a pair of dice 10000 times for each possible total.");
System.out.println ("It will then create a table for the average number of rolls it took to achieve that total.");
System.out.println ();
for (i = 2; i <= 12; i ++) {
averageNumberOfRolls = computeRoll (i);
averageTable [i] = averageNumberOfRolls;
}
System.out.println ("Total On Dice Average Number of Rolls");
System.out.println ("------------- -----------------------");
for (i = 2; i <= 12; i ++) {
System.out.println (" " + i + " " + averageTable [i]);
}
System.out.println ();
}
/*
This method will roll two dice randomly until it achieves 10000 rolls. It will record the
average number of rolls it took.
*/
private static int computeRoll (int goal) {
int dice1;
int dice2;
int result;
double attempts;
double numberOfTimesGoalWasHit;
double average;
numberOfTimesGoalWasHit = 0.0;
attempts = 0.0;
do {
result = 0;
dice1 = (int)(Math.random () * 6) + 1;
dice2 = (int)(Math.random () * 6) + 1;
result = dice1 + dice2;
attempts ++;
if (result == goal) {
numberOfTimesGoalWasHit ++;
}
} while (attempts < 10000.0);
average = attempts / numberOfTimesGoalWasHit;
return average;
}
}As the title says this is the main error I'm having trouble with and I can't figure out how to fix it. I'm also not sure how to call the mean function from the main function. I saw a similar post on here about this but it didn't help much. Before you laugh at my most likely horrible code, I know I'm terrible at java. Full disclosure, this is for homework so you don't have to do it for me just someone please explain how to fix this cause I've racked my brain for at least 2 hours and also looked up a ton of possible solutions but still couldn't fix it. So here's what I have so far after running around in circles for like 2 hours:
import java.util.Scanner;
public class Mean {
public static double mean(double[] array){
Scanner sc = new Scanner(System.in);
System.out.print("What is the size of the array? ");
double num = sc.nextDouble();
double total = 0.0;
for (double i = 0.0; i <= 100; i++) {
Scanner numbers = new Scanner(System.in);
double nums = numbers.nextDouble();
array[i] = nums;
total = array[i] + array[i];
total = array[i] / total;
}
return total;
}
public static void main(String[] args){
System.out.print("The average of these 5 numbers is " + array);
}
}
And here's the assignment parameters and examples:
Create a function double mean(double [] ...) that accepts an array, and returns the average (mean) of the values.
Write a program to test your function; read up to 100 floating-point values into an array, call your function to calculate the average and then print the average to two decimal digits. Sample runs are shown below.
What is the size of the array? 5
5 6 7 8 9
The average of these 5 numbers is 7.00.
What is the size of the array? 10
5.4 3.2 5.7 9.0 0 2.3 1.5 6 9 10
The average of these 10 numbers is 5.21.
So if anyone can help me with this by 09/23 that would be great cause I'm about at my breaking point with it.