简体   繁体   English

使用Scanner类nextLine()方法从文件中读取单词

[英]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 该列表一直持续到从'z'开始的最后一个单词,并且没有空行

列表一直持续到从'z'开始的最后一个单词。没有空行

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) 线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:java.lang.String.charAt(未知源)为0,而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. 仅当nextLine()方法在带有if条件的行中返回空字符串时才会发生这种情况,但是我读取的文件中没有空行。如果我将nextLine()方法的每个实例替换为next ()方法在程序中,它可以完美工作。请详细说明导致此异常发生的细节。

  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();
   }

 }

It is you second nextLine() that is causing the problem. 是第二个nextLine()导致了问题。 It moves to the next spot in the array. 它移动到阵列中的下一个位置。 You do that twice per loop (in the while loop). 您每个循环执行两次(在while循环中)。

So if you change: 因此,如果您更改:

alpha_list.println(dictionary.nextLine());

to

alpha_list.println(incre);

You would run out of bound. 您将超出范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM