我在if else语句中遇到了逻辑问题。
String[] keywords = { "day", "What book", "office", "hour",
"e-mail" };
Scanner scanner = new Scanner(System.in);
String input = null;
/* -end init- */
System.out.println("Welcome ");
System.out.println("What's on your mind?");
do {
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
for (String keyword : keywords) {
if (input.contains(keyword)) {
parseFile(keyword);
}
else {
Writer();
}
}
break;
} while (input.equalsIgnoreCase("bye"));
System.out.println("Have a good day!");
}
}
由于某种原因,忽略了第一个IF语句。有人可以给我一些建议。感谢
答案 0 :(得分:2)
使用map会减少每次检查整个数组的循环次数。
答案 1 :(得分:1)
我尝试运行该程序并且运行良好。如果我输入day
作为输入。然后它进入if
一次,进入其他地方(关键字-1的长度)时间。请检查您是否输入的值与关键字数组中的值相同。
package myApp;
import java.util.Scanner;
public class Client{
public static void main(String[] args) {
String[] keywords = { "day", "Cs 377", "What book", "office", "hour",
"e-mail", "name", "major", "student e-mail", "group id",
"lectures", "lecture room", "lecture time",
"number of lectures", "current lecture",
"topics of current lecture", "number of test",
"date of a test", "number of assignments", "sure",
"current assignment", "due day" };
Scanner scanner = new Scanner(System.in);
String input = null;
/* -end init- */
System.out.println("Welcome ");
System.out.println("What's on your mind?");
do {
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
for (String keyword : keywords) {
if (input.contains(keyword)) {
System.out.println("KEYWORD:" + keyword);
break;
}
else {
System.out.println("KEYWORD not found");
}
}
break;
} while (input.equalsIgnoreCase("bye"));
System.out.println("Have a good day!");
}
}
我用sysout替换了if和else中的一些东西。 我输入了一天,得到了以下结果。
Welcome
What's on your mind?
> day
KEYWORD:day
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
KEYWORD not found
Have a good day!
这个输出非常容易理解。如果您觉得困难,请评论您在下面遇到的问题。