在数组中搜索课程

时间:2016-05-05 20:54:02

标签: java arrays string substring

这是算法,但我在解密过程中遇到了困难 :

set flag equal to false
set index equal to 0

WHILE(index is less than number of courses in array AND flag == false)
    extract substring
    IF(string1.equals(string2) == true) THEN //course found
        set flag to true
    ELSE
        increment index
    END IF
END WHILE

IF flag == false THEN
    display message the course name was not found
ELSE
    course name found at position index
END IF

这是我的代码:

public void searchCourse(String courseName)
{
    int index;
    String extract;
    boolean notFound = false;
    index = 0;
    while(index < SIZE)
    {
        extract = schedule[index].charAt(0,6);
        if (courseName == extract){

        }
        else {
            index ++;
        }
        if ( notFound == false){
            System.out.println("Course Not Found");
        } 
        else{
            System.out.println("Course Found at: " + index);
        }
    } 
}    

3 个答案:

答案 0 :(得分:2)

伪代码似乎不必要复杂。

这就足够了:

public void searchCourse(String courseName) {
    for(int i = 0; i < schedule.length; i++) {
        if(courseName.equals(schedule[i].substring(0, 6))) {
            System.out.println("Course Found at: " + i);
            return;
        }
    }

    System.out.println("Course Not Found");
}

无论如何,正确的翻译应如下所示:

public void searchCourse(String courseName) {    
    boolean flag = false;
    int index = 0;

    while(index < schedule.length && !flag) {
        String extract = schedule[index].substring(0,6);
        if (courseName.equals(extract)){
            flag = true;
        } else {
            index++;
        }
    }

    if (!flag){
        System.out.println("Course Not Found");
    } else {
        System.out.println("Course Found at: " + index);
    }
}  

答案 1 :(得分:1)

您的代码必须与伪代码类似。

  • 在伪代码中,while循环有两个条件,你的代码只有一个。你使用&amp;&amp;在java中创建AND,因此它变为&& ! notFound
  • 在第一个if条件中,您必须将标志设置为true。这是一个简单的做法notFound = true

顺便说一句,该标志应该是found而不是notFound,但除了可读性之外,它不会改变任何内容。

答案 2 :(得分:0)

这里是正确的代码

 public void searchCourse(String courseName)
 {
    int index;
    String extract;
    boolean notFound = false;
    index = 0;
    while(index < SIZE)
    {
        notFound = false;
        extract = schedule[index].charAt(0,6);
        if (courseName == extract){
               notFound = true;
        }        
        if ( notFound == false){
            System.out.println("Course Not Found");
        } 
        else{
            System.out.println("Course Found at: " + index);
        }
        index ++;
    } 
}