2

I have a problem with my code,I get this error all the time:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:907)
    at java.util.Scanner.next(Scanner.java:1416)
    at audio.AudioSecrets.main(AudioSecrets.java:32)
Java Result: 1

my problem is this ligne:

contents = new Scanner(file).useDelimiter("\\Z").next().toCharArray(); // 

The \\Z delimiter in combination with .next() will read input until there isn't any left.

how can I input the file to my program,thanks for help

Jonas
  • 121,568
  • 97
  • 310
  • 388
Lina
  • 451
  • 1
  • 8
  • 23
  • It looks like you're trying to put the whole file into a String. This is dealt with at [What is simplest way to read a file into String?](http://stackoverflow.com/questions/3402735/what-is-simplest-way-to-read-a-file-into-string) which is why I voted to close as a duplicate of that one. It's not that this is a bad question - it's a good one. It's just that this has been done before. – Dawood ibn Kareem Mar 28 '14 at 05:05

1 Answers1

5

You should check hasNext() before calling next(). Probably there are no elements matching your criteria.

Scanner s = new Scanner(file);
s.useDelimiter("\\Z");
if(s.hasNext()) {
   contents = s.next().toCharArray();
}
sanbhat
  • 17,522
  • 6
  • 48
  • 64