我正在开展一个项目,要求我为大学加载一些课程。每门课程由课程名称(例如“CSCI 150”,“CSCI 150L”)和章节编号(前“CSCI 150 1”,“CSCI 150L 1”)组成。
我正在尝试使用这些课程加载arrayList,但每次我尝试在之后显示它们时,我会收到输入不匹配异常或Nosuchelement异常
以下是我的代码看起来像我正在使用的文本文件来测试它。
public class Prog6 {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
School university = new School();
File aFile = new File("prog6.txt");
Scanner fileReader = new Scanner(aFile);
String courseName;
int section;
int numberEnrolled;
while(fileReader.hasNextLine()){
courseName = fileReader.next() + fileReader.next();
section = fileReader.nextInt();
Course aCourse = new Course(courseName, section);
university.addCourse(aCourse);
}
university.displayCourses();
}
}
文本文件看起来完全像这样:
CSCI 150 1
CSCI 150 2
CSCI 150L 1
CSCI 140 1
MATH 174 1
MATH 132 2
MATH 412L 1
MATH 174 2
BIOL 110 1
BIOL 210 1
CBAD 310L 1
CBAD 110 1
CBAD 210 2
答案 0 :(得分:0)
我没有编译它,可能会有一些小的语法错误,但这应该可以解决问题。
import java.util.regex.*;
import java.util.Scanner;
public class Prog6 {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
School university = new School();
File aFile = new File("prog6.txt");
Scanner fileReader = new Scanner(aFile);
String courseName;
int section = -1;
int numberEnrolled;
String currentLine = "";
String regex = "(\\S+)(\\s)(\\S+)(\\s)(\\d)";
Pattern regexPattern = Pattern.compile(regex);
Matcher matcher;
while(fileReader.hasNextLine()){
courseName = "";
currentLine = fileReader.nextLine();
try {
matcher = regexPattern.match(currentLine);
matcher.find();
courseName = matcher.group(1) + matcher.group(3);
section = Integer.parseInt(matcher.group(5));
} catch (Exception e) {
System.out.println(e.getMessage());
}
Course aCourse = new Course(courseName, section);
university.addCourse(aCourse);
}
university.displayCourses();
fileReader.close();
}
}