问题
I am having an issue with my logic in my if else statements.
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!");
}
}
For some reason the first IF statement is ignored. Can someone give me some suggestions. Thanks
回答1:
using map will reduce the looping for whole array for every time to check if .
回答2:
I tried running the program and it worked well. If suppose i entered day
as input. Then it goes inside if
once and inside else for (length of keywords-1) time. Please check if you are not entering the value same as given in keywords array.
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!");
}
}
I replaced few things inside if and else with sysout. I entered day in input and got following result.
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!
This output is very well understandable. If you find it difficult, comment the problem you face below.
来源:https://stackoverflow.com/questions/29586401/if-else-statements