1

I'm trying to read some data out of a file, and then plug that into a Currency constructor and a couple other variables, but I'm getting errors. The relevant section of code:

public Bank(String fileName) {
    Scanner fileReader = new Scanner(fileName);
    bankName = fileReader.nextLine();
    commissionRate = fileReader.nextDouble();

    //setup each currency
    currency1 = new Currency(fileReader.next(), fileReader.nextDouble());
    currency2 = new Currency(fileReader.next(), fileReader.nextDouble());
    currency3 = new Currency(fileReader.next(), fileReader.nextDouble());
}

Here's the error:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextDouble(Unknown Source)
at project3.Bank.<init>(Bank.java:16)

Some googling tells me this means its not able to read the file correctly. It works up to the bankName = fileReader.nextLine() part, but everything after that fails. And I can't see why its not able to find the next whatever, since the files its supposed to read look something like this:

First Fake Bank 
1.1 
MXN 1.1 
EUR 1.2 
JPY 118.7 

The structure is one line of string, then a double under that, then three lines with a string followed by a double.

Makoto
  • 96,408
  • 24
  • 164
  • 210
brickmack
  • 21
  • 2
  • 1
    The `nextDouble()` method doesn't consume the line, you will have to consume the entire line to get to the next one. [More details](http://stackoverflow.com/questions/13102045/skipping-nextline-after-using-next-nextint-or-other-nextfoo-methods) – Titus Nov 16 '15 at 17:24
  • have you tried firing a `fileReader.nextLine();` after `bankName = fileReader.nextLine();`? – thegauravmahawar Nov 16 '15 at 17:26
  • The question is actually not a duplicate, since the problem is not in the usage of `Scanner`s method, but rather in the constructor used. You use the constructor for `String`, namely `Scanner(String source)`. This means that you basically open a `Scanner` for the specified `String`, in your case `fileName` and not for the file. You have to replace it with `Scanner fileReader = new Scanner( new File(fileName));` with the proper exception handling. – Ivaylo Toskov Nov 16 '15 at 17:31
  • @Titus, I tried 'commissionRate = Double.parseDouble(fileReader.nextLine());', but this time I still got an error. No line found – brickmack Nov 16 '15 at 17:34
  • You don't have to do that, you will have to add a `fileReader.nextLine()` after each `Currency` constructor. – Titus Nov 16 '15 at 17:35
  • 1
    @Titus, this is not correct. The `next` method will automatically look up the next line, after the end of the current one is reached. His problem is the improper usage of the constructor. – Ivaylo Toskov Nov 16 '15 at 17:37
  • @Ivaylo thanks, that worked. Derped and forgot about needing the new File bit – brickmack Nov 16 '15 at 17:44

0 Answers0