我正在编写一个程序,该程序的核心功能是做两件事:
但是我有两个主要问题: 1.给定我文件的格式,数组实际上是否充满了数据? 2.如何找到包含所有数据的特定学生?
这是文件格式(.txt):
ExampleName
ExampleSurname
2000年1月1日
男性
ExampleAddress
ExampleYear
数学,科学,英语,远程教育,地理,历史
然后再添加另一组数据。
要阅读此内容,这是我的方法:
//Method that will fill the array we created
public static void fillStudentArray(ArrayList<Student> students)
{
int size = 0;
File file = new File("/Users/cool/Desktop/Student Details.txt");
try
{
Scanner readFile = new Scanner(file);
while(readFile.hasNextLine())
{
firstName = readFile.next();
surname = readFile.next();
dob = readFile.next();
gender = readFile.next();
address = readFile.next();
form = readFile.next();
timetable = readFile.next();
students.add(new Student(firstName, surname, dob, gender, address, form, timetable));
size++;
System.out.println(size);
System.out.println("fillStudentArray in try section");
}
}
catch(FileNotFoundException exception)
{
exception.printStackTrace();
}
}
我再问一次,如果不是这样的话,这种方法是否可以有效地填充数组列表?
第二部分是我遇到更多困难的地方。 它的目的是读取用户输入,使用它遍历数组,然后打印所有学生数据,但是,它不起作用以及为什么我不确定。
这是我使用的方法:
//We can retrieve specific data from the array using this method
public static void searchStudentData(ArrayList<Student> students, Scanner userInput, Student StudentData)
{
while(true)
{
System.out.println("Enter the Student Name: ");
String stringUserInput = userInput.next();
for(int i = 0; i < students.size(); i++)
{
if(FirstName.equals(stringUserInput) || Surname.equals(stringUserInput))
{
System.out.println(StudentData(FirstName, Surname, DoB, Gender, Address, Form, Timetable));
break;
}
else
{
System.out.println("Error, please try again.");
continue;
}
}
}
}
我如何使这种方法起作用?我在哪里出错了,该如何解决?
我的完整代码: https://pastebin.com/9jnykFe9
答案 0 :(得分:0)
这甚至可以编译吗?在if(FirstName.equals(stringUserInput) || Surname.equals(stringUserInput))
中,您假设FirstName
和Surname
是变量,但不是。您要使用的是students.get(i).firstName
,因为您需要ArrayList中当前Student
的名字。然后它应该工作。
此处有简短的旁注。在上部,size
可以省略变量students.size
。
希望这会有所帮助。