如果第一个单词与用户输入匹配,则需要打印出数组行

时间:2015-12-06 08:16:52

标签: java

我有一个包含由txt文件制作的课程的数组:

arr[1] = CSC 110 Fundamentals of Programming I
arr[2] = PHYS 102 General Physics
arr[3] = MATH 100 Calculus I
arr[4] = CSC 167 Video Game Interaction and Design
arr[5] = ECON 103 Principles of Microeconomics

我的方法:

public static void listCoursesInDept(String targetDept, UvicCourse[] arr){}

获取部门名称(例如:csc)并搜索数组以查找包含部门的行。如果描述名称与数组中的名称匹配,则打印整行(部门,编号和名称)。

我想知道如何将targetDept与第一个单词或数组中的每一行进行比较。

1 个答案:

答案 0 :(得分:1)

更好的方法是将它们存储在地图中并使用密钥获取值。

Map<String, String> departments = new HashMap<String, String>();
String findKey = "CSC1";
departments.put("CSC", "CSC 110 Fundamentals of Programming I");
departments.put("PHYS", "PHYS 102 General Physics");
departments.put("MATH", "MATH 100 Calculus I");

if(departments.containsKey(findKey))
{
    System.out.println( findKey + " --- " + departments.get(findKey));
}
else
{
    System.out.println("Invalid Couse");
}

更新

使用数组是类似的,你必须利用字符串方法。

List<String> departments = new ArrayList<String>();
String findKey = "CSC1";
departments.add("CSC 110 Fundamentals of Programming I");
departments.add("PHYS 102 General Physics");
departments.add("CSC 167 Video Game Interaction and Design");
boolean found = false;
for(String department : departments)
{
    if(department.startsWith(findKey))
    {
        found = true;
        System.out.println(department);
    }
}
if(!found)
{
    System.out.println("Invalid Cource");
}