Tuesday, July 28, 2009

Just putting the finishing touches, please help me finalize this code?

import java.util.Scanner;


import java.io.File;


import java.io.IOException;


import java.io.FileWriter;


public class Average{


public static void main(String[]args)


{


int count=0;


int average=0;


long sum=0;


Scanner in=null;





File F= new File("C:\\Users\\Owner\\Documents\\My Documents\\JAVA\\Lesson 13\\numbers.txt");//remember to change this at skool





try{


in= new Scanner(F);





while (in.hasNext()){


String number = in.nextLine();


sum=sum + Long.parseLong(number);//string value to long value


count++;


//writing part need to work on this








}


average=sum/count;//possible loss of precision error here


FileWriter out = new FileWriter("C:\\Users\\Owner\\Documents\... Documents\\JAVA\\Lesson 13\\Average.txt");


String one= ""+average;


one.write(average);//compiler says cannot find this method


one.close();//cannot find this method either





} catch(IOException i){


System.out.println("Error: File does not exist");


}


}





}

Just putting the finishing touches, please help me finalize this code?
"//possible loss of precision error here"


Consider using a float for your average variable and cast count to a float so that it does not do an integer division





"//compiler says cannot find this method "


Possibly because you've called the variable "one" by mistake. I'm sure its meant to be "out"





"//cannot find this method either"


Ditto





I would also close the Scanner object by called


in.close();


when you are done with it


No comments:

Post a Comment