|
Re: Help,,How can i read data from file to int or float???
|
Posted: Nov 26, 2003 5:16 AM
|
|
Sure it doesn't work.
Did you ever look at the readLine() - Syntax in the Java API? This Method only delivers Strings (you ARE using a BufferedReader of some type, right?).
a=datas.elementAt(1)+datas.elementAt(2);
would not even work if readLine would deliver something else than String, because you obviously store the data in a Vector. A Vector can't store primitive Datatypes like float, int, double, only Classes extending the class Object (like Float, Integer, Double, String, ... = everything except primitive datatypes). The Method getElementAt() delivers your data as Object, to do something useful with it, you have to cast it to it's original Cass type.
Your file does NOT contain 5.6, but "5.6"
What you have to do? 1. To get something useful from the Vector, you must convert the term to String: (String)datas.elementAt(1) //delivers for example the String "1.333" wich is not equal to 1.333
2. You have to PARSE the text you got from the file, wich in this case would be: Float.parseFloat ((String)datas.elementAt(1))
Your addition example looks would look like this: float a = Float.parseFloat ((String)datas.elementAt(1)) + Float.parseFloat ((String)datas.elementAt(2));
If your Vector contains only Strings with float-Values, you can use the following method to convert it do an array of floats.
private float[] toArray (Vector v) throws NumberFormatException { float a[] = new float[v.size()]; for (int i = c.size()-1; i >= 0; i--) a = Float.parseFloat ((String)datas.elementAt(i)); }
There is no error correction in this method (it assumes every value is String and can be parsed to float), but you WILL have to implement it.
Call
float f[]; try { f = toArray(datas); } catch (NumberformatException e) { //do something useful }
The try-catch Code is to catch Errors (TRY , if [Exception] occurs, execute the code in CATCH). Now you can access your float Values with f[i] float a = f[1] + f[2];
|
|