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]);
}
}
}