Hey Guys I am using a list of lists in java.The list is called deg_grp and the code below shows the output of the deg_grp at a particular index j.
for(int k=0;k<deg_grp.get(j).size();k++)
{
System.out.println(deg_grp.get(j).get(k));
}
The output is:
1.0
2.0
4.0
6.0
8.0
So these are my values. But when I replace the print command by
System.out.println((int)deg_grp.get(j).get(k));
It is throwing me an error.I need to perform int conversion for indexing purposes later on.The error is:
incompatible types: Float cannot be converted to int
So I am unable to run the code. Kindly help me out. Thanks :)
Use Float#intValue() for your conversion.
You can't unboxed and convert types in one step. You can do (int)(float) f however I suggest not using Float, use double or Double for more precision and using Math.round(d) to round the result, to minimise errors.
System.out.println(Math.round(deg_grp.get(j).get(k)));
Related
Using java 11 and Intellij Idea.
I'm in the situation where I get a string of data from an external system and need to reformat this. In the current setup I have this line to extract the value for a sales price:
BigDecimal sellingPrice = BigDecimal.valueOf(Double.parseDouble(somesalesprice));
According to the debugger, the output value of sellingPrice = "4.350000000"
Now when I convert this according to this line of code:
long roundedSellingPrice = (long) (sellingPrice.doubleValue() * 100);
the result turns out to be "434". As can be seen, 1 (cent) has magically disappeared. I double-checked the values and this consistent. Out of the 500+ dataset that I'm working with, approx. 40 other records seem to have this problem. For the majority it seems to be going just fine.
I cannot find anything common between these records.
Also, it turns out, the result is always rounded down by 1 cent, never up.
Wonder what this could be?
As weird as it sounds for the data of types Float and Double the precision is not very good. Use BigDecimal for all the calculations. That's the short answer.
In Addition, when you parse a String to any numerical type you have to deal with exceptions. Sometimes it makes sense and sometimes it doesn't. For the case when you don't care about exception I wrote a utility that parses string to any numeric value and if parsing fails it returns a default value. In case you want your exception messages to be printed into log the same utility optionally may print exception messages into a log. See methods:
public static java.math.BigDecimalparseStringToBigDecimal(java.lang.CharSequence num, java.math.BigDecimal defaultValue) and
public static java.math.BigDecimal parseStringToBigDecimal(java.lang.CharSequence num,
java.math.BigDecimal defaultValue,
java.lang.String nullOrEmptyStringErrorMessage,
java.lang.String numberFormatErrorMessage)
Those methods can be pretty useful. The utility is comes with Open Source MgntUtils library written and maintained by me. You can get it as maven artifacts or at Github
I am reading Excel data using java apache. I got format issue while reading double value such as 869.87929 (in excel) into 869.8792899999999 (in java).
I'm using following files to read excel data.
1. Schema.csv: SheetName,2-int-Double
2. File.xls:
col1 | col2
123 | 869.87929
Sample code:
if(type.equals("Double")){
Double fval=Double.parseDouble(content[i-1]);
String sval=fval.toString();
listObjects.add(new Double(Double.parseDouble(sval)));
}
Note: type from schema.csv & content [] value from file.xls
There is no point converting number back and forth to Strings as this shouldn't do any thing useful.
Try doing
listObjects.add(new BigDecimal(content[i-1]));
with rounding you can do
listObjects.add(new BigDecimal(content[i-1]).setScale(9, RoundingMode.HALF_UP));
though I suspect the rounding error has occurred before this point as this should do basically the same thing as
listObjects.add(new Double(content[i-1]));
with rounding you can do
double d = Double.parseDouble(content[i-1]);
double round9 = Math.round(d * 1e9) / 1e9;
listObjects.add((Double) round9);
These are much the same as the number is within the precision of double and there should be no additional error here (i.e. the error is likely to be before this point)
Double is not good for preserving precision. Preffered is using BigDecimal. I believe this is your problem.
https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal
If you use Apache POI - you can use getCellType()==Cell.CELL_TYPE_NUMERIC comparison and getNumericCellValue() from Cell interface.
I'm creating an Android app, and I'm reading some coordinates from a text file.
I'm using Integer.parseInt(xCoordinateStringFromFile) to convert the X coordinates to integers, and in the same way with the Y coordinates.
When I run the app, I get an error on that line, which looks like this:
BridgeData data = new BridgeData(
elements[0],
elements[1],
Integer.parseInt(elements[2]),
Integer.parseInt(elements[3]),
Integer.parseInt(elements[4]),
new GeoPos(Integer.parseInt(elements[5].split(",")[0]), Integer.parseInt(elements[5].split(",")[1])),
new GeoPos(Integer.parseInt(elements[6].split(",")[0]), Integer.parseInt(elements[6].split(",")[1])),
Integer.parseInt(elements[7]),
Integer.parseInt(elements[8])
);
The variable elements is a String array created by splitting the current line on every ;.
The "main" error is:
java.lang.NumberFormatException: Invalid int: "3546504756"
I wonder what this means, and how I can solve it.
Error just means that java is not able to convert the String that you are trying to use in your call to Integer.pasrseInt as that number is out of range of an integer.
You should be using Long.parseLong as 3546504756 number is out of range of an integer.
Make sure post that your BridgeData constructor accepts long as a parameter instead of integer.
Revising the concept of data type and their size might help you
http://www.tutorialspoint.com/java/java_basic_datatypes.htm
In Java, an int is 32 bits, which is enough to store numbers up to just over 2 billion. The number you were trying to read was an invalid int because it was too big.
I would seriously question the design of whatever you are doing, if you have coordinates with values of over a billion. But if you really need such big numbers, use long in place of int in your BridgeData class, and Long.parseLong in place of Integer.parseInt in the code that you quoted.
The range of int value can be lies between -2,147,483,648 to 2,147,483,647 and you are providing it more than that thats why it giving numberformatexception
You have to store the value in either long or other more range premetive type.
You can find more about java premetive data type range and value here
i have a java code for finding out netsalary . I keep Getting "bad operand type for binary operator ' / '" error . The Line goes like this
netSalary = Double.parseDouble(principle2*rate2/12*Math.pow(rate2/12+1))/(Double.parseDouble(Math.pow(rate2/12+1)-1));
Could this be solved . Thanks in advance!
It should be commas you use, not slashes.
Math.pow(rate2/12+1) should syntactically be in the form of Math.pow(x,y) where both x and y are doubles. The first arg is the base, and second arg is the index you're raising it to. As the comment below mentioned, it's difficult to understand what you're trying to achieve, and you'll have to substitute x and y for the correct values - make sure they're of type double (you cannot use, for example, 12+1 as a parameter because it is an integer). If it is an integer, then type cast it using (double) in front of the value.
You also do not need to parseDouble everywhere since Math.pow will return double values anyways; it is redundant.
I agree with the comment above; please read the javadocs for any problems you're having with a method before posting here.
You mistake in using power function your power function should be like this
Math.pow((rate2/12+1),1)
I'm new to Java, and I'm using Processing to make some data visualizations. I'm getting this strange error in my code though, was wondering if anyone could help me out. It seems the Xspacing float keeps getting set to Infinity, however when I print out the expression it gets set to the proper value gets printed...
float Xspacing = (endX-(width*.04) - startX)/ values;
println((endX-(width*.04) - startX)/ values);
println(Xspacing);
Result is:
49.0
Infinity
Any help would be appreciated!
Sorry, I wrote this out very quickly and omitted some pretty necessary info:
49.0 IS what is should be. All other types are floats, besides values which is an integer.
The code DOES compile, and println is build into Processing, which is the framework (correct term?) that I'm using. It is basically a function that prints to the console in the Processing GUI.
Xspacing was intended to be data for my class "Graph," however when I define the variable within a public function "drawBasic" everything works fine. Now I am just curious....
Using System.out.println(0 yields the same results. Initial values or variables are:
float startX = 120.00001
float endX = 740.0
int values = 12
width is an integer (although not explicit) that is set to 800
The odd thing seems to be that within a function definition this works fine, its only when I try to define it within the class that it doesn't work...
Your code couldn't be like that because a number *.04 creates a double, and that would mean you'd need to cast the expression into a float.
For your code to compile it would have to be something like
float Xspacing = (float)((endX-(width*.04) - startX)/ values);
println((endX-(width*.04) - startX)/ values);
println(Xspacing);
Now, on the result. If your code had, for example:
System.out.println(3/0);
Java would give you a java.lang.ArithmeticException: / by zero
However, if you have
System.out.println(3f/0);
Then Java will give you "Infinity". Why? http://grouper.ieee.org/groups/754/
Try this:
float Xspacing = (endX-(width*.04) - startX)/ values;
println((float)((endX-(width*.04) - startX)/ values));
println(Xspacing);
float Xspacing = (endX-(width*.04) - startX)/ values;
Even assuming the variables are floats that line does not compile, because of the 0.4 double literal.
Also 'println' is not a standalone method, so you must have written your own.
What is your actual code?
you forget a ) and you should've put System.out.println(xspacing);
fyi you can also just type syso and ctrl spacebar and it will print out the print statement for you.