首页 > 解决方案 > 在数组中搜索字符串出现的次数

问题描述

在我的 java 类中,我们使用 junit test 来测试我们的方法。本节介绍使用接口。

我遇到问题的这个特定方法应该在每个索引处搜索一个数组,寻找一个匹配的字符串作为输入。

在junit测试中我有

    void test() 
    {
        MyClassList labTest = new MyClassList("CIS 120", "Fall", "Professor Awesome");

        MyStudent george = new MyStudent("George","Lucas", "555-555-5555","george.lucas@starwars.com");
        MyStudent gene = new MyStudent("Gene", "Roddenberry","666-666-6666", "gene.roddenberry@startrek.com");
        MyStudent jordan = new MyStudent("Jordan" ,"Robberts", "755-555-5555", "jordan.robberts@wheeloftime.com");

        labTest.insert(george);
        labTest.insert(gene);
        labTest.insert(jordan);

        System.out.println(labTest.toString());
        System.out.println(labTest.contains(george));
        System.out.println(labTest.search("George"));

这是您用于方法搜索的代码:

笔记

 protected MyStudent [] log;
 protected int lastIndex = -1;

是全局变量

package Lab2;

import java.util.Arrays;
import java.util.Scanner;

import Lab2.ClassListInterFace;

public class MyClassList implements ClassListInterFace {
    protected String course;
    protected String semester;
    protected String teacherLastName;
    protected MyStudent[] log;
    protected int lastIndex = -1;

    public MyClassList(String currCourse,  String currSemester, String lastName, int maxSize) {
        log = new MyStudent[maxSize];
        this.course = currCourse;
        this.semester = currSemester;
        this.teacherLastName = lastName;
    }

    public MyClassList( String currCourse,  String currSemester, String lastName)

    {
        log = new MyStudent[100];
        this.course = currCourse;
        this.semester = currSemester;
        this.teacherLastName = lastName;
    }

    public void insert(MyStudent element) {
        lastIndex++;
        log[lastIndex] = element;
    }

    public boolean isFull() {
        if (lastIndex == (log.length - 1))
            return true;
        else
            return false;
    }

    public int size() {

        return (lastIndex + 1);
    }


    public void clear() 
    {
          for (int i = 0; i <= lastIndex; i++)
              log[i] = null;
            lastIndex = -1;

    }

    public String getName() {
         return teacherLastName;
    }


public boolean contains(MyStudent element) {

    boolean found = false;
    for( int location = 0;location <= lastIndex; location++)
    {
      if (element.equals(log[location]))  // if they match
        found = true;
}
    return found;
}

public String toString()
{
    String message = "Course " + course + "\n Semester " + semester + "\n Proffessor " + teacherLastName + "\n"; 
            for (int i = 0; i <= lastIndex; i++) {
                message += log[i].toString();
            }
    return message;
}

public int search(String x) 

{
    int answer = 0;
     for(int i = 0; i < log.length; i++) 
     {
            if(x.equalsIgnoreCase(log[i]))
                answer++;
     }

    return answer;

}

我是根据老师给我们参考的一些代码得到的,我稍微调整了一下。

标签: javaarraysstring

解决方案


这看起来可以通过for循环更优雅地完成。根据我的经验,使用为此类事情设计的更简洁的控制结构可以大大减少出错的机会。虽然我不确定您要寻求帮助的确切问题是什么,但我确实注意到,如果您确实找到了匹配项,您会跳过下一个元素而不检查它是否也是匹配项。

    int location = 0;
    while (location <= lastIndex) 
    {
        if (x.equalsIgnoreCase(log[location])) 
        { // if they match
            answer ++;
            location ++;  //<-- Here's where you increment twice upon finding a match!
        }
        location++;  //To fix with the smallest number of changes, just put this in an else clause
    }

通过将其更改为for循环,可以将整个块减少到大约一半的行和一半的变量。见下文:

    for(int i = 0; i < log.length; i++) {
        if(x.equalsIgnoreCase(log[i].firstName))
            answer++;
    }

这更容易阅读,而且更不容易出错。试图跟踪过多的变量或划分常见操作(例如增加您所在的位置)只是在寻找问题。这个四行代码在功能上等同于您上面的代码块(除了它在找到匹配项时不会跳过以下条目的事实),但程序员犯错误的机会要少得多。始终,当您可以摆脱它时,请使用为任务设计的控制流结构。


推荐阅读