如何在Java中搜索数组

如何在Java中搜索数组,java,Java,我正在制作一个简单的java应用程序,它向用户询问他们需要导师的科目,然后打印教授该科目的导师 这是我到目前为止写的 包装公司 导入java.util.Scanner 公共班机{ public static void main(String[] args) { Scanner userInput = new Scanner(System.in); System.out.println("Enter the subject: "); String tut

我正在制作一个简单的java应用程序,它向用户询问他们需要导师的科目,然后打印教授该科目的导师

这是我到目前为止写的

包装公司

导入java.util.Scanner

公共班机{

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    System.out.println("Enter the subject: ");
    String tutorNeeded = userInput.nextLine();
    String[] theTutors = {"Phillip Banks: Mathematics", "William Smith: Physics", "Alex Ferguson: Computer Science", "Edwin Valero: Mathematics"};
    if (tutorNeeded.contains("Math")) {
        System.out.println("The tutor(s) for the following subject are: " + "\n" + theTutors[0] + "\n" + theTutors[3]);
    }else if (tutorNeeded.contains("Physics")) {
        System.out.println("The tutor(s) for the following subject are: " + "\n" + theTutors[1]);
    } else if (tutorNeeded.contains(("Computer"))) {
        System.out.println("The tutor(s) for the following subject are: " + "\n" + theTutors[2]);
    } else {
        System.out.println("Sorry, we don't have any tutors for that subject availible right now.");
    }
}
}


这段代码可以工作,但我想知道如果我必须输入大量新信息该怎么办。这太耗时了,因为我必须在主数组中输入新的tutor,还要输入print语句。如何提高效率?

如其中一条评论所述,您必须迭代数组。与此精神相同的东西:

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);
    System.out.println("Enter the subject: ");
    String tutorNeeded = userInput.nextLine();
    String[] theTutors = {"Phillip Banks: Mathematics", "William Smith: Physics", "Alex Ferguson: Computer Science", "Edwin Valero: Mathematics"};
    String foundTutors = "";
    for (String tutor: theTutors) {
        if(tutor.contains(tutorNeeded){
            foundTutors = "\n" + tutor;
        }
    }
    if (foundTutors.isEmpty()) {
        System.out.println("Sorry, we don't have any tutors for that subject availible right now.");
    }
    else {
        System.out.println("The tutor(s) for the following subject are:" + foundTutors);
    }
}

另一个想法是保存一张地图,将所有科目映射到教师列表。然后你可以很容易地扩展它。或者创建一个教师类,该类包含一个他教授的主题,然后保存一个教师列表。有很多很多方法可以实现这样的功能

欢迎来到堆栈溢出:您能展示一下您的尝试吗?你的代码中有什么地方卡住了吗?请相应地更新您的问题,请参见。重要的是,您要展示您所做的工作以及您遇到的问题。这就是堆栈溢出的本质—通过查看数组的不同元素来搜索数组,直到找到要查找的元素为止。没有更多关于手头具体问题的细节,很难说得更多。谢谢大家的提示!我将编辑我的主要问题