[英]java: Read text file and store the info in an array using scanner class
I have a text file include Student Grades like: 我有一个文本文件包括学生成绩如:
Kim $ 40 $ 45
Jack $ 35 $ 40
I'm trying to read this data from the text file and store the information into an array list using Scanner Class. 我正在尝试从文本文件中读取此数据,并使用Scanner Class将信息存储到数组列表中。 Could any one guide me to write the code correctly?
任何人都可以指导我正确编写代码吗?
import java.io.*;
import java.util.*;
public class ReadStudentsGrade {
public static void main(String[] args) throws IOException {
ArrayList stuRec = new ArrayList();
File file = new File("c:\\StudentGrade.txt");
try {
Scanner scanner = new Scanner(file).useDelimiter("$");
while (scanner.hasNextLine())
{
String stuName = scanner.nextLine();
int midTirmGrade = scanner.nextInt();
int finalGrade = scanner.nextInt();
System.out.println(stuName + " " + midTirmGrade + " " + finalGrade);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at writereadstudentsgrade.ReadStudentsGrade.main(ReadStudentsGrade.java:26)
Try useDelimiter(" \\\\$ |[\\\\r\\\\n]+");
试试
useDelimiter(" \\\\$ |[\\\\r\\\\n]+");
String stuName = scanner.next(); // not nextLine()!
int midTirmGrade = scanner.nextInt();
int finalGrade = scanner.nextInt();
Your problems were that: 你的问题是:
$
is a regex metacharacter that needs to be escaped $
是一个需要转义的正则表达式元字符 Your while
loop is off. 你的
while
循环关闭了。
nextLine()
will get you all what's left of the line and advance the cursor to there. nextLine()
将获取该行的所有内容并将光标前进到那里。 nextInt()
will then jump delimiters until it finds an int. 然后
nextInt()
将跳转分隔符,直到找到一个int。 The result will be skipping of values. 结果将是跳过值。
Assuming Kim and Jack were on different lines you would get: 假设金和杰克在不同的路线上你会得到:
stuName == "Kim $ 40 $ 45"
midTirmGrade == 35
finalGrade == 40
as your output; 作为你的输出; which isn't what you want.
这不是你想要的。
Either you need to use the end-of-line as the delimiter or use a StringTokenizer to break each line up and then parse each of the sections as individual tokens. 要么您需要使用行尾作为分隔符,要么使用StringTokenizer来打破每一行,然后将每个部分解析为单独的标记。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.