这是算法,但我在解密过程中遇到了困难 :
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);
}
}
}
答案 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)
您的代码必须与伪代码类似。
&& ! notFound
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 ++;
}
}