Elliander
Elliander

Reputation: 511

Trying to write a file to an Array - getting NoSuchElementException

(For this I need to use Arrays - not Array lists. Snipping code to make it easier to follow. Renaming variables and constants to label so others who read this later understand what I am doing better.)

At the class level I have my arrays defined like so:

private static final int CONSTANT = 20;
public static String[] arrayName = new String[CONSTANT - 1];

and in the main method I am pointing to the method like so:

readArrays("filenName.txt", arrayName);

and a line like that points to the following complete method which is where the error occurs:

    public static void readArrays(String codeFile, 
                                 String[] Arrays)
 {        

   try ( Scanner fin = new Scanner ( new File(codeFile) ); ) 
    {
     for (int i = 0; i < CONSTANT - 1; i++) 
          {
          Arrays[i] = fin.next();
          }
    }
    catch (FileNotFoundException e) 
    {
        System.err.println( "Read Error: " + e.getMessage() );
    }

It shows no errors in NetBeans, but in the console window the exact error message is:

 run:
 Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at mp06.Main.readArrays(Main.java:47)
    at mp06.Main.main(Main.java:33)
 Java Result: 1
 BUILD SUCCESSFUL (total time: 0 seconds)

What is causing this error? Ultimately, my goal is to write the entire contents of multiple text files to multiple arrays using the same method and without using any other approach.

Upvotes: 0

Views: 92

Answers (2)

Loganathan Mohanraj
Loganathan Mohanraj

Reputation: 1874

The below code might help you. There are couple of things, you have to check whether next element is exists in scanner before you call next() and the other one is the constant "20", it will end up with Array Index Bounds exception if the size exceeds 20.

Adding them in the list and converting them to an array will resolve this. Try the below code.

    List<String> list = new ArrayList<String>(); 
    while (fin.hasNext()) {
        list.add(fin.next());
    }

    String[] array = new String[list.size()];
    list.toArray(array);

    for (String str: array) {
        System.out.println(str);
    }

Upvotes: 1

chengpohi
chengpohi

Reputation: 14217

    try ( Scanner fin = new Scanner ( new File(codeFile) ); ) 
    {
     for (int i = 0; i < CONSTANT - 1 && fin.hasNext(); i++) 
          {
          Arrays[i] = fin.next();
          }
    }
    catch (FileNotFoundException e) 
    {
        System.err.println( "Read Error: " + e.getMessage() );
    }

You also need to check Scanner has next.

In Java8, you can use stream to read file:

List<String> contents = Files.lines(Paths.get("filenName.txt")).collect(Collectors.toList());

Upvotes: 3

Related Questions