Scanner - Exception in thread "main" java.util.NoSuchElementException: No line found

StackOverflow https://stackoverflow.com/questions/17317235

  •  01-06-2022
  •  | 
  •  

문제

There is definitely a line but I don't understand why cant the Scanner see it ..

Here is the beginning of the file :

256
<Y 1874>
<A T. HARDY‡<T Madding Crowd(Peuœ‚978)”C i”P 51‡DESCRIPTION OF FMERÅAK -- AÄINCIºNT

Below is my code for getting it:

File file = new File ("calgary/book1_enc");
Scanner first_line = new Scanner(file);
int size_st;
size_st = Integer.valueOf(first_line.nextLine());

But I am getting the error:

Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at LZWDecoder.main(LZWDecoder.java:26)

The file book1_enc is an output of my LZW encoding algorithm.When I am passing the file to my Decoder I would like the decoder to know the size of dictionary which is 256 in this case...Thanks for reading...

도움이 되었습니까?

해결책

The problem is with the encoding of the input file. Use the other constructor for Scanner that specifies a character set:

Scanner first_line = new Scanner(file, "UTF-8");

Using other constructors results in the default character set being used which typically cannot correctly read unicode characters.

Workaround:

BufferedReader br = new BufferedReader(new FileReader("book1_enc.dat"));
int sizeSt = Integer.parseInt(br.readLine());

다른 팁

It means that your file doesn't have next line. You should always check hasNextLine() before calling nextLine. You should modify your code like this

if (first_line.hasNextLine()){
    size_st = Integer.valueOf(first_line.nextLine());
}

java.util.NoSuchElementException is thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top