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, use hasnextdouble instead of hasnextint.

  • 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

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -