Why is variable displaying 0? - java

This is my first time using StackOverflow so sorry if my question is nooby as I am learning Java. What I am trying to do now is pass a variable from one method into another method(same class) so I can show the value in a graph. My code is below:
Method 2
private void Average(){
System.out.println(openessAverage);
DefaultCategoryDataset bc = new DefaultCategoryDataset();
bc.setValue(openessAverage, "Percentage", "Openess"); //Show here
JFreeChart jchart = ChartFactory.createBarChart3D("Big 5 Graph", "ID","Percentage" , bc, PlotOrientation.VERTICAL,true,true,false ); //chart
CategoryPlot plot = jchart.getCategoryPlot();
ChartFrame chartFRM = new ChartFrame("Personality Insight", jchart,true);
chartFRM.setVisible(true);
chartFRM.setSize(800,600); //Sets JFrame size
}
When I run that code it gives me 0.0 in the console and graph is also 0. Any idea why? would really appreciate the help:)

the reason is pretty simple
dividing integers will return an integer too.
therefore
double c = a/b;
will be zero if b > a
solution: cast one of the operands to double
double c = (double)a/b

The probelm has to do with the fact that you are dividing a double by an integer. Any time you do that, basically Java truncates the result (removes the decimal). In your case, the size of the list is probably greater than what it's dividing, so it's rounding down to 0. To fix this, you can either cast opennes.size() to a double, or better, just cast that operation to a double.
Double num = (double) num1/num2;
Hope that helps

Related

Big Error in Java or incongruency with simple operators

I'm beginning in Java, and could anyone explain me why Java gives me these answers?
I have a very simple class trying to learn how to round a number.
I want 2 decimals
so...
public static void main(String[] args) {
double pi1 = Math.PI;
System.out.println("pi1 = " + pi1);
double p2 ;
p2= Math.round(pi1*100)/100;
//p2= Math.round(pi1*100)
//p2=p2/100;
System.out.println("p2 = " + p2);
}
If I run this result is:
p2 = 3.0
Then I change
//p2= Math.round(pi1*100)/100;
p2 = Math.round(pi1*100);
p2 = p2/100;
Now, result is:
p2 = 3.14
as I wanted
Why with these differences? Why the first option doesn't give me 3.14
I think that I've made a correct code with 1st option.
Please, anyone could tell me why?
These things makes me don't trust Java.
Thank you.
I will assume that you know how integer division works in Java. In short, when both sides of / are integral types, like in 314 / 100, the expression evaluates to an integer too, like 3.
Math.round returns a long, which is an integral type. In your first code, you have the expression Math.round(pi1*100)/100. Math.round(...) returns an integer type, 100 is an integer literal, so integer division occurs.
However, in the second code, you first assigned the result of Math.round to p2. The long returned is implicitly converted to a double first, and stored in p2. You then wrote an expression in p2: p2/100. Here, one of the operands is double, so integer division does not occur.
Therefore, the one liner version that is the same as the second code is:
p2 = ((double)Math.round(pi1*100))/100;
You don't see the double conversion in the second code because it is done implicitly.
A note on rounding
This way rounding doubles should be used if you want to do calculations with the rounded number afterwards. If you just want to display a rounded number as output, you should use String.format, System.out.printf, or DecimalFormat. Read more about these methods here.
No mistake here, it works properly. Method Math.round(double) returns type long.
In your first variant, you receive result long 314 and divide it by 100 and get the result 3, and then assign it back to double.
In your second variant, you receive long result 314 and assign it back to double. Dividing double keeps precision as opposed to dividing long, so you get the correct result of 3.14
There for make p2= Math.round(pi1*100)/100; as
p2= Math.round(pi1*100) / 100.0;
Output -:
pi1 = 3.141592653589793
p2 = 3.14

BigDecimal to String in java?

My code is:
x=new BigDecimal(x.toString()+" "+(new BigDecimal(10).pow(1200)).toString());
I am trying to concat two bigdecimals after converting them to string and then convert them back to bigdecimal.I am doing so because x has a value with a decimal point and multiplying will change its value.It compiles fine but throws a numberformat exception on execution.
My idea was to use the BigDecimal("String x") constructor to convert the string back to BigDecimal.
Note:
(for example)
x=1333.212
and I am converting it to
x=1333.2120000
It's failing to parse because you've got a space in there for no particular reason. Look at the string it's trying to parse, and you'll see it's not a valid number.
If you're just trying to add extra trailing zeroes (your question is very unclear), you should change the scale instead:
x = x.setScale(x.scale() + 1200);
Simple example:
BigDecimal x = new BigDecimal("123.45");
x = x.setScale(x.scale() + 5);
System.out.println(x); // 123.4500000
If you were trying to multiply the value by a power of 10 (as your initial question suggested), there's a much simpler way of doing this, using movePointRight:
x = x.movePointRight(1200);
From the docs:
The BigDecimal returned by this call has value (this × 10n) and scale max(this.scale()-n, 0).
You need to try in this way
BigDecimal result=new
BigDecimal("1333.212123232432543534324243253563453423423242452543535")
.multiply(new BigDecimal("10").pow(1200));
System.out.println(result);
For your Edit:
BigDecimal result=new
BigDecimal("1333.212123232432543534324243253563453423423242452543535")
.multiply(new BigDecimal("10").pow(1200));
System.out.println(result.movePointRight(-1200));

Why double width = 50/110000; the output is 0.000000000000000?

This is my code :
double width = 50/110000;
System.out.println("width ori is "+width );
And the output is: 0.00000000000
What's wrong ? the expected output has to be 4.5454545454545455E-4
Any body can explain to me why?
Because you're dividing two integers, so it will only take the integer part (integer division).
Dividing integers in a computer program requires special care. Some
programming languages, treat integer division (i.e by giving the integer quotient as the answer). So the answer is an integer.
Examples :
In real life In Java
4/3 = 1.33333 4/3 = 1
25/12 = 2.083333 25/12 = 2
9/2 = 4.5 9/2 = 4
50/110000 = 0.000454545 50/110000 = 0
You can cast one of the number (or both but it's actually useless) to double to avoid that :
double width = (double)50/110000;
double width = 50d/110000;
double width = 50.0/110000;
Result of int/int returns you an integer.
So the decimal part got truncated resulting you with an integer
You need to cast:
double width = (double)50/110000;
As #Josh M has pointed, You can also try :
double width = 50d / 110000d;
Explanation to what's happening:
In Java, the default type of numbers is int, so when you write 50/110000, they're both considered int, although you defined the result to be double.
When int division occurs, the result will be 0, because they are both ints, then the double will hold this value, which will be represented as double, so you're getting 0.000000.
Possible solutions:
Coding these numbers with d: 50d/110000d.
Casting one side explicitly (the other will be implicitly cast): (double)50/110000.
50.0/110000.
See Chapter 5. Conversions and Promotions, it'll really help you.

Casting a double result from a divison into an int in Java

I want to use a method that requires an int. This int is determined by a division potentially solved as a double. I need to perform this as neat and short as possible and I am wondering if I can count that the method will take the double directly casted as int and if this means a single truncation with no roundings.
Do I have to necessarily use Math static methods?
Could this give errors for non int parameter entries to subList?
Could someone provide any guidance about this?
List<Integer> b = null;
List<Integer> c = null;
int size = a.size();
b.addAll(a.subList(0, size / 2)); // To hold the first half
c.addAll(a.subList(size / 2, size)); // To hold the second half [and excess]
Thank you in advance for your help.
it will take the double casted to integer and will not round it, just disregard everything after the "."
so if the division of 9.8/2 is 4.9 then you'll get 4 for doing
int x = 9.8/2;
you don't need to use the Math static methods for devision and you won't get errors for the code you gave
to conclude, you can just run your code and see if the result is as you want it.
b.addAll(a.subList(0, size / 2));
should run without problem
What's wrong with b.addAll(a.subList(0, (int)(size / 2)));?

Java / Android - equation for rounding up

I am building an android application. In my app, i need to be able to round up a double (42.42 for example) and also get how much i added to the original number in order to round it up. My current code isn't working, and its outputting 0.. Anyway to fix this?
My current code:
float rounded = FloatMath.ceil(val);
double getDecimal = (val - FloatMath.floor(val))*100;
int noDecimal = (int) ((int) 100-getDecimal);
float toadd = (noDecimal/100);
In my code the "rounded" variable is the simpel rounding, and "toadd" should be how much i added to it. For some reason toadd always comes back as 0. Any help?
You're dividing noDecimal by 100. Both are ints, and the result will always be an int. In this case, it's an int between 0 and 1, which will always be truncated to 0.
What's wrong with just getting the number modulo 1 (%1), then getting the ceiling of the original number?
For completeness, you could simply change the last line to preserve the rest of the logic:
float toadd = noDecimal/100.0;
This changes the divisor to a float, and an int divided by a float yields a float.
float toadd = (noDecimal/100);
This will give you 0, as you are dividing smaller integer by larger one..
Try to do like this: -
float toadd = (Float.valueOf(noDecimal)/100);
Also, you don't need to do typecast twice in the below code: -
int noDecimal = (int) ((int) 100-getDecimal);
Just, outer cast is enough: -
int noDecimal = (int) (100-getDecimal);
Edit: - Also, you might want to use BigDecimal for this kind of problems..
Maybe I'm missing something or not getting your intention right, but if you just want to know what you added, why don't just use the difference?
float rounded = FloatMath.ceil(val);
float toadd = rounded-val;
Edit: As mentioned in the comments, this might not always give the absolutely accurate result. But it's the general idea which can be used with BigDecimal, which offers a higher precision.

Categories