[英]Java: Error with reading in file with delimiter
I have a file with multiple fields that i need to store individually into an array. 我有一个包含多个字段的文件,需要分别存储到数组中。
Steve;stiffy;123;88
Sam;sammy;456;55
But when i try storing them i keep getting error saying java.util.NoSuchElementException 但是当我尝试存储它们时,我总是收到错误消息说java.util.NoSuchElementException
Here is my code for storing the data 这是我用于存储数据的代码
void loadCustomer(){
try {
Scanner sc = new Scanner(new File("CustomerInfo.txt"));
sc.useDelimiter(";");
while (sc.hasNext())
{
cusName.add(sc.next());
cusUser.add(sc.next());
cusPass.add(sc.next());
cusCCNum.add(sc.next());
}
}
I could get it to work by changing 我可以通过更改来使其工作
cusCCNum.add(sc.next());
to 至
cusCCNum.add(sc.nextLine());
but it will ignore the delimiter and when i print out cusCCNum.get(1), it will display 但是它将忽略定界符,并且当我打印出cusCCNum.get(1)时,它将显示
;88
instead of 代替
88
Where did i go wrong? 我哪里做错了?
88和Sam之间没有分隔符。
scanner.useDelimiter(";|\n");
You are causing the exception while you are calling the 4 next elements for each one check if there is 1 next element, this would do the following: 您在为每个检查一个下一个元素调用4个下一个元素时引发异常,这将执行以下操作:
while (RecentElement is not the last one)
{
Read (RecentElement + 1)
Read (RecentElement + 2)
Read (RecentElement + 3)
Read (RecentElement + 4)
}
And somewhen you get the exception of the next() method because you access an element that is just not there: 还有,当您获得next()方法的异常时,因为您访问的元素并不存在:
Throws: NoSuchElementException - if no more tokens are available
抛出:NoSuchElementException-如果没有更多令牌可用
You should use the new line as a delimiter and for each new line parse the data from the record, for example using the split function: 您应该使用新行作为分隔符,并为每条新行解析记录中的数据,例如使用split函数:
sc.useDelimiter("\n");
while (sc.hasNext())
{
for(String g: sc.next().split(";"))
System.out.println(g);
}
Looks like you need to read each line, token it using delimeter and set values to array. 看起来您需要读取每一行,使用分号对它进行标记并将值设置为array。
I could do it via StringTokenizer. 我可以通过StringTokenizer做到这一点。
while (sc.hasNextLine()) {
StringTokenizer st = new StringTokenizer(sc.nextLine(),";");
while (st.hasMoreElements()) {
System.out.println(st.nextElement());
}
}
I am surprised and need to read more on Scanner api to see why its not working with scanner. 我很惊讶,需要阅读有关Scanner api的更多信息,以了解为什么它不适用于扫描仪。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.