【发布时间】:2020-05-20 12:22:31
【问题描述】:
我有一个从 cvs 文件读取的 java 程序,如下所示:
1111,John,23
2222,Mary,32
...
我想将每个字段存储在一个数组中。每当我运行以下程序时,我都会收到以下消息:
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)
我该如何处理该异常?我猜这是因为扫描仪读取超出了它的限制,但是,while 块不确保它会在它的限制内读取吗?
感谢任何帮助
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]);
}
}
}
【问题讨论】:
-
您发布了整个错误吗?通常它也表示行号
-
你说得对,我现在正在编辑我的帖子
标签: java file exception java.util.scanner