我是第一个 Java 编程任务的初学者。对于我们的编程作业,我们将获得一个学生的 .txt 文件,如下所示:
我的问题是:我有一个特定的类,用于将文件中的数据转换为变量,以用于将其打印到屏幕上的不同类。但是,我不知道从输入文件中获取课程编号的变量的好方法,因为该编号不是预先确定的。我能想到的迭代未知数量的唯一方法是使用循环,但这只会覆盖我的变量。另外,老师要求我们不要使用任何 JCL 课程(我真的不知道这是什么意思。)
抱歉,如果我解释得不好,但我想不出更好的方法来概念化它。让我知道我是否可以澄清。
编辑:
public static void analyzeData()
{
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("Programming Assignment 1 Data.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("File Programming Assignment 1 Data.txt could not be found or opened.");
System.exit(0);
}
int numberOfStudents = inputStream.nextInt();
int tuitionPerHour = inputStream.nextInt();
String firstName = inputStream.next();
String lastname = inputStream.next();
String isTuitionPaid = inputStream.next();
int numberOfCourses = inputStream.nextInt();
String courseName = inputStream.next();
String courseNumber = inputStream.next();
int creditHours = inputStream.nextInt();
String grade = inputStream.next();
为了展示我现在使用的方法,我只是使用 Scanner 从文件中读取数据,对于 Scanner inputStream,我使用 nextInt() 或 next() 从文件中获取变量。显然,当我不知道每个学生将有多少个班级时,这将不起作用。