简体   繁体   中英

Java issues with Scanner and hasNextLine() while reading a file

I am having an issue with this unfinished program. I do not understand why this returns a "no Line found exception" when I run it. I have a while loop set up whose purpose is checking for this but I have done something wrong. I am trying to store information from a file into a 2d array for class.

import java.util.Scanner;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.util.Arrays;

public class LabProgram {
   public static void main(String[] args) throws IOException {
      Scanner scnr = new Scanner(System.in);
      int NUM_CHARACTERS = 26;      // Maximum number of letters
      int MAX_WORDS = 10;           // Maximum number of synonyms per starting letter
      String userWord = (scnr.next()) + ".txt"; //Get word user wants to search
      char userChar = scnr.next().charAt(0); //Get char user wants to search
      String[][] synonyms = new String[NUM_CHARACTERS][MAX_WORDS];  // Declare 2D array for all synonyms
      String[] words = new String[MAX_WORDS]; // The words of each input line
      
      File aFile = new File(userWord);
      
      Scanner inFile = new Scanner(aFile);
      
      while(inFile.hasNextLine()) {
         for(int i = 0; i < synonyms.length; i++) {
            words = inFile.nextLine().trim().split(" ");
            for(int wordCount = 0; wordCount < words.length; wordCount++) {
               synonyms[i][wordCount] = words[wordCount];
            }
         }
      }
      
   }
}

The issue is with this for loop:

for (int i = 0; i < synonyms.length; i++) {
    words = inFile.nextLine().trim().split(" ");
    ....
}

You're iterating from i=0 upto synonym.length-1 times, but that file does not have these much lines, so, as soon as your file is out of lines but the for loop has scope to iterate more, the inFile.nextLine() gets no line and thus throw the exception.

I don't know what you are exactly doing here or want to achieve through this code, but this is what causing you the trouble.

Hope that answers your query.

Basically your problem is that you're only checking hasNextLine() before the for loop starts, and you're actually getting the next line on every iteration of the loop. So if you run out of lines while in the middle of your for loop an exception is thrown.

I'm actually not quite sure what your code is supposed to do but at the very least you need to add a hasNextLine() check every time before you actually run nextLine() to avoid errors like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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