在我的程序中,我要求用户输入主题名称和主题代码,我将其传递到 subject.txt 文件,例如:
TestSubject 类内部 -
//ask the user to input a subject name
System.out.println("Please enter a Subject Name");
//assign each input to a side
String subjectName = input.nextLine();
//ask the user to input a subject code
System.out.println("Please enter a Subject Code");
String subjectCode = input.nextLine();
//add records to the file
subject.addRecords(subjectName, subjectCode);
在学科类别内 -
//add the records of valid subject name and subject code
public void addRecords(String name, String code) {
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("subjects.txt", true)))) {
out.printf(name);
out.printf("\n");
out.printf(code);
out.printf("\n");
out.close();
}catch (IOException e) {
}
}
然后我想读取该文件并将数据传递到数组列表。该文件可能类似于:
Testing 1
ABC123
Testing 2
DEF456
Testing3
GHI789
我想将它传递给一个数组列表,这样我就可以针对这个数组处理其他方法,例如排序,看看是否有相同的等等。
//read data from subjects file and place in an array
public void readData(){
Scanner input = new Scanner("subjects.txt");
while (input.hasNext()) {
String subjectName = input.nextLine();
String subjectCode = input.nextLine();
}
ArrayList<String> subjectNames = new ArrayList<String>();
ArrayList<String> subjectCodes = new ArrayList<String>();
//add the input to the arrays
subjectNames.add(subjectName);
subjectNames.add(subjectCode);
//display the contents of the array
System.out.println(subjectNames.toString());
System.out.println(subjectCodes.toString());
}
即使有一个很好的教程,我也许能够指出正确的方向......
最佳答案
感谢您编辑您的帖子。当我能看到问题的根源时,提供帮助就容易多了。
您每两行检查一次 hasNext() 。应该检查每一行,因为您不应该相信文本文件是您所期望的,并且应该在它不是时显示一条信息丰富的错误消息。
您还在循环范围内声明了字符串,因此循环之外的任何内容都不会知道它们是什么。将 subjectCode 插入 subjectNames 集合可能不是您想要的。事实上,每个 nextline() 都会步进到最后一个字符串值。这意味着您忘记了在循环的先前迭代中完成的所有工作。
collections.add() 调用,而不是字符串,应该在循环中。确保在循环之前声明集合并将其添加调用放入循环中。看看您是否获得有用的结果。
关于java - Java从文件中读取数据到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23717554/