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;
}
}
I'm working on a school project right now and I am getting an error which I have no idea how to fix. Any help is appreciated
package Assignment_3_1; //directory
import Media.*;
import static java.lang.Math.*;
import static java.awt.Color.*;
public class Forest{ //class
private TurtleDisplayer display; //display
private Turtle t; //pen
public Forest(){ //constructor
//instance/global variables
display = new TurtleDisplayer(); //initialize display
t = new Turtle(0); //initialize pen
display.placeTurtle(t); //place the pen on the display
drawLeaves(30);
display.close(); //close display
}
private void drawLeaves(double radius){ //this method draws trees' leaves given a double radius (width of leaves)
for(int i = 0; i <=7; i++){ //repeat the below code a set number of times
//below code draws a line, 45 degrees the right of the previous one
t.setPenWidth(radius*2.0);
t.setPenColor(GREEN);
t.right(PI/4);
t.penDown();
t.forward(radius);
t.penUp();
t.backward(radius);
}
}
private void drawTrunk(double height){ //draws a trunk given a double height
}
public static void main(String[] args){Forest s = new Forest();};
}The error happens at line:
t.setPenWidth(radius*2.0);
Once again, I have no idea what's happening here
The method setPenWidth probably takes an integer parameter. Your radius is a double. In order to use the radius value for the method Java needs to convert it to an integer by cutting the decimal digits off. So your value might lose accuracy.
Please ensure that:
-
Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
-
You include any and all error messages in full
-
You ask clear questions
-
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Code blocks look like this:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.