in java, i have an array of floats, some of them are negative numbers, like :
3.04, 9.02, -4.2, -3.21, 0.02, -0.34
I only want to get the float numbers higher than 2, so I used :
if(number > 2.0 ) print.. etc
but what i get is not only the numbers>2, also the negative numbers :
3.04, 9.02, -4.2, -3.21
what could be the problem ?
3 Answers 3
It's hard to tell what the problem is without seeing code. Writing the obvious code from your description, it works fine:
public class Test {
public static void main(String[] args) {
float[] floats = { 3.04f, 9.02f, -4.2f, -3.21f, 0.02f, -0.34f };
for (float number : floats) {
if (number > 2.0) {
System.out.println(number);
}
}
}
}
Compare your code with mine - if you still can't get yours to work, please edit your question with your code.
Comments
Based on comments and question, assuming we have a file named numbers.txt with content:
3.04 9.02 -4.2 -3.21 0.02 -0.34
this code should do the trick (I ommited exception handling for readibility):
float[] floats = new float[100]; // adjust as needed
String fileName = "numbers.txt";
File f = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = "";
int i = 0;
while( (line = br.readLine()) != null) {
if(line == null || line.isEmpty()) continue; // just in case there are empty lines in file
floats[i] = Float.parseFloat(line);
i++;
}
br.close();
for (float number : floats) {
if (number > 2.0) {
System.out.println(number);
}
}
Output:
3.04 9.02
Comments
This is too long for a comment but it should be pointed out that if you write:
if (number > 2.0)
then you probably shouldn't be working with floating-point numbers because you don't understand yet how they work.
There's a good Wikipedia page on floating point numbers:
http://en.wikipedia.org/wiki/Floating_point
Then I suggest reading the 80 pages long "What every computer scientist should know about floating-point numbers".
Basically: due to the limited precision of floating point numbers, comparison should typically always be done using an epsilon.
Things like: if (number> 2.0) are a big no-no.
3 Comments
< and > is usually not so critical (this of course depends on the domain, the range of values etc.). And overall, this is definitely not an answer to the original question - it would have been better to squeeze it into a comment.BigDecimal anyway.)
what could be the problem ?Looks to me like you took the absolute value of the numbers before the test.Stringtofloat... are you remembering to take the sign in as you parse the string? You should show us the code that assignsnumberand the part that prints it.