With A SpiRIT
With A SpiRIT

Reputation: 538

Issue reading words from a file using Scanner class nextLine() method

I have a text file that contains collection of words from the English language.The words are written in alphabetical order with a single word on a line and with no empty lines , no punctuation etc . The list looks like as shown in the image below. The list continues till the last word starting from 'z' and there are no empty Lines whatsoever

The list continues till the last word starting from 'z'. There are no empty Lines whatsoever

I have made a simple program that reads words from this file line by line and writes the words on different files.The problem is that I am getting this error

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(Unknown Source) at sd.main(sd.java:27)

This could only happen if the nextLine() method returns an empty string in the line with the if condition.But I have no blank lines in the file from which I am reading.If I replace every instance of the nextLine() method with next() method within the program, it works flawlessly.Kindly enlighten me with the details causing this exception to occur.

  import java.io.* ;
  import java.util.*;

  public class sd {

  public static void main(String[] argue)  throws java.io.IOException {

     char incre = 97 ;
     File diction = new File("C:/Users/LoRd CuRZon/Desktop/dictionary/wordsEn.txt") ;
     PrintWriter alpha_list = new PrintWriter("C:/Users/LoRd CuRZon/Desktop/dictionary/a.txt") ;
     Scanner dictionary = new Scanner(diction) ;
     Scanner dictionarytemp = new Scanner(diction) ;

     while(dictionary.hasNextLine()) {

         if((char)incre != ((dictionarytemp.nextLine()).charAt(0)))  {      
            alpha_list.close();
            incre++ ;
            alpha_list = new PrintWriter("C:/Users/LoRd CuRZon/Desktop/dictionary/" + (char)incre + ".txt" ) ;
         }

     alpha_list.println(dictionary.nextLine());

      }

      alpha_list.close();
      dictionary.close();
   }

 }

Upvotes: 0

Views: 259

Answers (1)

Michael
Michael

Reputation: 2631

It is you second nextLine() that is causing the problem. It moves to the next spot in the array. You do that twice per loop (in the while loop).

So if you change:

alpha_list.println(dictionary.nextLine());

to

alpha_list.println(incre);

You would run out of bound.

Upvotes: 1

Related Questions