Java read contents from a file and apply to formula -
trying read contents of file , apply formula
e.g if file contains
7
9.50
1.25
the output be
€7.0 = £5.46
€9.5 = £7.41
€1.25 = £0.975
my code:
import java.io.*; import java.util.scanner; public class filequestion { public static void main (string[] args) throws ioexception { file filecontents = new file("currencyfile.txt"); scanner inputfile = new scanner(filecontents); if(filecontents.exists() == false ) { system.out.println("file doesnt exist "); } else{ while(inputfile.hasnextint()) { double result; double conversionrate = 0.78; result = ?? * conversionrate; system.out.println("£" + filecontents + " = €" + result); } inputfile.close(); } } }
you don't know how read file, right? it's easy. if have used scanner
before, should know there method called nextdouble
returns next double
value. should use method.
just replace ??
inputfile.nextdouble()
.
however, there few more problems code.
since file contains
double
values, usehasnextdouble
instead ofhasnextint
.you should check whether file exists before creating
scanner
. otherwise throw exception.you shouldn't print
filecontents
. instead, should put value got file in variable, print variable.
here's code:
file filecontents = new file("currencyfile.txt"); if(!filecontents.exists()) { system.out.println("file doesn't exist "); } else{ scanner inputfile = new scanner(filecontents); while(inputfile.hasnextdouble()) { double result; double conversionrate = 0.78; double currencyfrom = inputfile.nextdouble(); result = currencyfrom * conversionrate; system.out.println("£" + currencyfrom + " = " + "€" + result); } inputfile.close(); }
Comments
Post a Comment