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 |
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 |
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; Code:
float total = 0.0F; |
All times are GMT -5. The time now is 10:39 PM. |