0

All I am trying to do is create an array from numbers in a file... I'm pretty new to java so it may not be the most efficient way but I'm going off limited knowledge for now.

When I run it, I get the following message:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at CreateArray.main(CreateArray.java:27)

Here is my feeble attempt at the code:

import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;

public class CreateArray
{
  public static void main(String[] args) throws IOException
  {
    File file = new File("Numbers.txt");
    Scanner inputFile = new Scanner(file);

    // Find the number of lines in the file
    int count = 0;
    while (inputFile.hasNextLine())
    {
      String str = inputFile.nextLine();
      count++;
    }

    // Create array
    double[] numbers = new double[count];

    // Add numbers to array
    String str;
    while (inputFile.hasNextLine());
    {
      for (int i = 0; i < count; i++)
      {
        str = inputFile.nextLine();
        numbers[i] = Double.parseDouble(str);
      }
    }

    // Display array
    for (int i = 0; i < numbers.length; i++)
      System.out.print(numbers[i] + " ");
  }
}
  • 1
    Your scanner already reached the end fo the file using the first while loop, so there is nothing there for the second while loop. Either close and reopen the file in between loops or combine the loops. – tima Jul 25 '17 at 18:09

2 Answers2

1

When you write inputFile.hasNextLine() in your code using scanner, You have actually read a line from the file.
As @tima said, you completed reading the file in the first while loop. Try looking at this java: about read txt file into array

Anupama Boorlagadda
  • 1,158
  • 1
  • 11
  • 19
1

Use Collection like ArrayList .So at time of File reading you don't need to declare size of array.

File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
List<Double> myList = new ArrayList<Double>();

while (inputFile.hasNextLine()) {
    String str = inputFile.nextLine();
    try {
        myList.add(Double.parseDouble(str));
    } catch (NumberFormatException e) {
        // TODO: handle exception
    }
}

for (Double data : myList) {
    System.out.println(data);
}

And if you need array type ,then use this :-

Double data[] = new Double[myList.size()];
    myList.toArray(data);

    for (int i = 0; i < data.length; i++) {
        System.out.println(data[i]);
    }
Alok Mishra
  • 1,904
  • 1
  • 17
  • 18