0

I have a java program that reads from a cvs file that looks like this:

1111,John,23
2222,Mary,32 
...

I want to store each field in an array. Whenever I run the following program I get the following message:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)

How can I deal with that exception? I guess it is because scanner reads beyond its limit, however, doesn't the while block ensure that it will read within its limits?

Any help is appreciated

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

public class program
{
    public static void main(String[] args) throws FileNotFoundException, IOException
    {
        BufferedReader br = new BufferedReader(new FileReader("info.csv"));
        int[] ids = new int[20];
        String[] names = new String[20];
        int[] age = new int[20];

        String line;
        int i = 0;
        while( (line = br.readLine()) != null)
        {
            Scanner s = new Scanner(line).useDelimiter(",");
            ids[i] = s.nextInt();
            names[i] = s.next();
            sales[i] = s.nextInt();
            s.close();
            i++;
        }

       for(int j = 0; j < 20; j++)
       {
           System.out.println("Id: "+ids[i]+" Name: "+names[i]+" Age: "+ age[i]);
       }
    }
}
user47
  • 141
  • 7
  • Did you post the whole error? Usually it also says the line number – Francesco May 20 '20 at 12:26
  • 1
    Does this answer your question? [What is java.util.NoSuchElementException and how do i fix it?](https://stackoverflow.com/questions/28249102/what-is-java-util-nosuchelementexception-and-how-do-i-fix-it) – maio290 May 20 '20 at 12:27
  • you are right I am editing my post right now – user47 May 20 '20 at 12:27

2 Answers2

2
  1. Reading CSV files is actually quite complicated. Handling quotes and newlines is quite difficult. There are also encoding issues to consider (which you haven't; you should basically never use this constructor FileReader, as it uses 'platform default encoding'). Don't reinvent this wheel; use something like super-csv.

  2. The while block ensures you read each line once and don't read beyond the end of the file. Per line you forcibly go: an int, a string, and an int, period. That's where the crash occurs. Mostly likely there's a trailing newline at the end of the file or some such. A trivial example would be to check if line.trim() is empty, and if so, to just move on (continue;) and not attempt to read the line.

But, really, don't handroll this, get a CSV parser.

NB: If you must reinvent this wheel, there are far nicer and easier ways to get all lines from a file. For example, Files.newBufferedReader(Paths.get("/path/to/whatsit")) or even Files.lines(Paths.get("/path/to/whatsit")), conveniently those methods also default to UTF-8, i.e. a consistent choice instead of 'flip a coin and pray'.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • I really disagree with the first part. Reading CSV files is a very easy task since you usually don't have to build a jack of all trades device here. One of my "more" complex solutions is about 100 lines. In one class. No overhead needed for an additional library which is just adding yet another library. – maio290 May 20 '20 at 13:27
1

Try to use split(,)

            String[] split = line.split(",");
            if (split.length >= 0) {
                String input = split[0];
                if (input.matches("[0-9]+"))
                    ids[i] = Integer.parseInt(input);
            }
            if (split.length >= 1) {
                names[i] = split[1];
            }

            if (split.length >= 2) {
                String input = split[2];
                if (input.matches("[0-9]+"))
                    ids[i] = Integer.parseInt(input);
            }
0xh3xa
  • 4,801
  • 2
  • 14
  • 28