这个程序的基本功能是用一个单词搜索一个字符串数组而不是搜索并打印包含该单词的字符串。
public static void main(String[] args) {
String[] str = {"I am Alive.", "Are you dead?", "Let's see if it works."};
String search;
int count=0;
Scanner s=new Scanner(System.in);
System.out.println("enter word");
search=s.nextLine();
for(int i=0;i<str.length;i++){
//check strings individually
if(str[i].charAt(i)=='.'||str[i].charAt(i)=='?'){ //search for dot or any sentence finisher
count++;
}
if(str[i].contains(search)){
System.out.println(str[count]);
} else {
System.out.println("Not found");
break;
}
}
}
答案 0 :(得分:0)
注意break
,它始终执行。
检查一下:
public static void main(final String... args) {
final String[] strings = { "I am Alive.", "I am Alive...too.", "Are you dead?",
"Let's see if it works." };
int found = -1;
System.out.print("Enter search term > ");
try (final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name())) {
final String input = scanner.nextLine();
for (int i = 0; (i < strings.length) && (found < 0); i++) {
if (strings[i].contains(input) && (strings[i].contains(".") ||
strings[i].contains("?"))) {
//System.out.println(strings[i]);
found = i;
}
}
}
System.out.printf("%s%n", (found >= 0) ? strings[found] : "Not found");
}
答案 1 :(得分:0)
你不应该在那里打破循环,因为一旦你完成了数组中的所有句子,它就被认为是找不到的。像这样:
public static void main(String[] args) {
String[] str={"I am Alive.","Are you dead?","Let's see if it works."};
String search;
Scanner s=new Scanner(System.in);
System.out.println("Enter word");
search=s.nextLine();
boolean found = false;
for(int i=0;i<str.length;i++){
if(str[i].contains(search)){
System.out.println(str[i]);
found = true;
}
}
if (!found) {
System.out.println("Not found");
}
}