简体   繁体   中英

A Java Scanner Exception

I am trying to write a program where I take a textfile and copy it to another file. In this other file I want one word on the first line, two words on the second, three on the third and so on.

I am having some trouble with the Scanner class however. In the program below I keep getting a NoSuchElementException for line 14. I thought this was because I closed the Scanner in the while loop or something but even when I left out 'in.close()' I kept getting the same error.

Can anybody help me with this?

Thanks in advance.

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

public class WordPyramid {
   public static void main(String[] args) throws FileNotFoundException {
      File inputFile = new File(args[0]);
      Scanner in = new Scanner(inputFile);
      PrintWriter out = new PrintWriter(args[1]);
      int s = 1;
      int i = 0;
      while (in.hasNext()) {
        if (s >= i) {
           for (i = 1; i <= s; i++) {
              out.print(in.next());
              out.print(" ");
            }
        out.println("");
        s++;
        }
    }
  in.close();
  out.close();
  }
}

A NoSuchElementException is thrown when there is no next() element. While you check to see if the file hasNext() at the start of each layer of the pyramid, you also need to check it before you call next() in the for loop. Your exception is thrown in the for loop because the next layer of the pyramid may require a larger number of words than remains in the file causing next() to try and get an element that is not there.

To fix it, wrap the interior of you for loop with if(in.hasNext()) .

hasNext() checks if there is one more token in the scanner's stream. You are checking if there is one more token, and then assuming there are even more than one in your for loop. I would modify your for loop to look like this:

for (i = 1; i <= s && in.hasNext(); i++)

I would like to suggest that your loops are perhaps over-complicated.

Here is what I think is an easier answer, and avoids your exception:

File inputFile = new File(args[0]);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(args[1]);
int s = 1;
int i = 0;
while (in.hasNext()) {
  out.print(in.next() + " ");
  i++;
  if (i == s)
  {
     // Start the next line
     out.println();
     s++;
     i = 0;
  }
}

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