问题描述
问题是这样的1.1.我们现在需要增加一条来让我们能从输入文件读取和计算平均值。a)创建一个FileReader对象b)创建一个BufferedReader对象2.写primingread来读取文件的第一行。3.写一个循环读取直到最后一行4.循环主题包括:a)转换至double的值并且添加值到accumulator中b)正向计数c)从文件中读取新的行5.当程序退出事关闭input文件6.计算平均值,平均值由accumlator除计数得来。7.运行,输出平均值为77.444这是其中的一步,我不明白的是4.a那一步,怎么才能把行转换成double的值??由于楼主电脑是mac身边也没windows的操作系统。。完全不能检验,一下是我写的代码importjava.text.DecimalFormat;//fornumberformattingimportjava.util.Scanner;//forkeyboardinputimportjava.io.*;//forusingfilespublicclassStatsFile{publicstaticvoidmain(String[]args)throwsIOException//ADDATHROWSCLAUSEHERE{doublesum=0;//thesumofthenumbersintcount=0;//thenumberofnumbersaddeddoublemean=0;//theaverageofthenumbersdoublestdDev=0;//thestandarddeviationofthenumbersStringline;//alinefromthefiledoubledifference;//differencebetweenthevalueandthemean//createanobjectoftypeDecimalFormatDecimalFormatthreeDecimals=newDecimalFormat("0.000");//createanobjectoftypeScannerScannerkeyboard=newScanner(System.in);Stringfilename;//theuserinputfilename//PrompttheuserandreadinthefilenameSystem.out.println("Thisprogramcalculatesstatistics"+"onafilecontainingaseriesofnumbers");System.out.print("Enterthefilename:");filename=keyboard.nextLine();//CreateaPrintWriterobjectpassingittheFileWriterobject.PrintWriteroutFile=newPrintWriter(filename);outFile.print(mean+"");outFile.print(stdDev+"");outFile.close();//ADDLINESFORTASK#2HERE//CreateaFileReaderobjectpassingitthefilenameFileReaderreader=newFileReader(filename);//CreateaBufferedReaderobjectpassingittheFileReaderobject.BufferedReaderin=newBufferedReader(reader);//primingreadtoreadthefirstlineofthefileStringinputLine=in.readLine();//createaloopthatcontinuesuntilyouareattheendofthefilewhile(inputLine!=null){//convertthelineintoadoublevalueandaddthevaluetothesum//incrementthecounter//readanewlinefromthefile}//closetheinputfile//storethecalculatedmean//ADDLINESFORTASK#3HERE//reconnecttotheFileReaderobjectpassingitthefilename//reconnecttotheBufferedReaderobjectpassingittheFileReaderobject.//reinitializethesumofthenumbers//reinitializethenumberofnumbersadded//primingreadtoreadthefirstlineofthefile//loopthatcontinuesuntilyouareattheendofthefile//convertthelineintoadoublevalueandsubtractthemean//addthesquareofthedifferencetothesum//incrementthecounter//readanewlinefromthefile//closetheinputfile//storethecalculatedstandarddeviation//ADDLINESFORTASK#3HERE//createanobjectoftypeFileWriterusing“Results.txt”//createanobjectofPrintWriterpassingittheFileWriterobject.//printtheresultstotheoutputfile//closetheoutputfile}}
求指导!!
解决方案
解决方案二:
这不就是String转double嘛,多简单,doubled=Double.parseDouble(inputLine);inputLine=in.readLine();
解决方案三:
引用1楼wu244534279的回复:
这不就是String转double嘛,多简单,doubled=Double.parseDouble(inputLine);inputLine=in.readLine();
不知道为什么书上没有例子,实在是不明白i/o的东西,讲exception的时候有稍微提到一点,但是没有深入,不知道为什么会留下这种作业。不过谢谢指点!