LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Basic Java arithmetic question (https://www.linuxquestions.org/questions/programming-9/basic-java-arithmetic-question-70307/)

chr15t0 07-05-2003 01:06 PM

Basic Java arithmetic question
 
I'm just starting out with Java, but I'm having problems getting the following to compile. I have searched around and tried all sorts of things, but it seems hard to get floats from the args[] array.. Am I doing something badly wrong?

I get the error:

FloatTest.java:10: variable total might not have been initialized
total+=found;
^

----------- code : -----------

import java.lang.*;

class FloatTest{
public static void main(String args[]){
float total;
for(int i=0;i<args.length;i++){
// collect arg and sum to total
float found=Float.valueOf(args[i]).floatValue();
System.out.println("you sent in "+found);
total+=found;
System.out.println("total is now "+total);
}
}
}


thanks,

christo

chr15t0 07-05-2003 01:30 PM

fixed by initlaising the variables at the same time as declaring them:


import java.lang.*;

class FloatTest{
public static void main(String args[]){
float total=0.0f;
float found=0.0f;
for(int i=0;i<args.length;i++){
// collect arg and sum to total
found=Float.valueOf(args[i]).floatValue();
System.out.println("you sent in "+found);
total=(total+found);
System.out.println("total is now "+total);
}
}
}


there y' go


christo

TheLinuxDuck 07-05-2003 01:32 PM

Firstly, when posting code, wrap the code in [code] [/code] tags. This makes reading the code easier, as it preserves indentation. (=

Secondly, the error is caused by the fact that total was not assigned an initial value.

The code declares total, but later tries to add to it's current value (by +=) without it ever having been given a defined initial value.

If you change
Code:

    float total;
to
Code:

    float total = 0.0F;
that will solve the error.


All times are GMT -5. The time now is 10:39 PM.