java:使用扫描仪类读取文本文件并将信息存储在数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2440103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java: Read text file and store the info in an array using scanner class
提问by Amateur
I have a text file include Student Grades like:
我有一个包含学生成绩的文本文件,例如:
Kim $ 40 $ 45
Hyman $ 35 $ 40
I'm trying to read this data from the text file and store the information into an array list using Scanner Class. Could any one guide me to write the code correctly?
我正在尝试从文本文件中读取此数据,并使用 Scanner Class 将信息存储到数组列表中。任何人都可以指导我正确编写代码吗?
Code
代码
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();
}
}
Runtime error:
运行时错误:
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)
回答by polygenelubricants
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:
你的问题是:
- You mistakenly read whole lineto get student name
$
is a regex metacharacter that needs to be escaped- You need to provide both line delimiters and field delimiters
- 您错误地阅读整行以获取学生姓名
$
是需要转义的正则表达式元字符- 您需要同时提供行分隔符和字段分隔符
回答by Smalltown2k
Your while
loop is off.
您的while
循环已关闭。
nextLine()
will get you all what's left of the line and advance the cursor to there.
nextInt()
will then jump delimiters until it finds an int.
The result will be skipping of values.
Assuming Kim and Hyman were on different lines you would get:
nextLine()
将为您提供该行剩余的所有内容并将光标移动到那里。
nextInt()
然后将跳转分隔符,直到找到一个整数。结果将是跳过值。
假设 Kim 和 Hyman 在不同的线路上,你会得到:
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 StringTokenizerto break each line up and then parse each of the sections as individual tokens.
您需要使用行尾作为分隔符,或者使用StringTokenizer将每一行分开,然后将每个部分解析为单独的标记。