Tezen Tezen - 1 year ago 81
Java Question

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

Answer Source

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()).