提问人:Matthew Grathwol 提问时间:11/24/2022 更新时间:11/28/2022 访问量:167
从扫描仪输入中选取单词
Picking a word from a scanner input
问:
您如何从字符串或扫描仪输入中选择单词,例如搜索引擎搜索?
我在 indexOf() 中查找了一个字符串,但我没有找到如何通过从一行文本中查找单词来制作一个公共 void 单词类。希望每个字都可以是一个变量。
答:
0赞
serafm
11/24/2022
#1
从你问的,这就是我的理解。具有新的 FindWord 对象、文本和对象方法的主类。名为 FindWord 的类,其方法名为 searchFor(),带有两个参数。第一个参数是要查找的单词,第二个参数是要搜索的文本。
public class Main {
public static void main(String[] args) {
// New object FindWord
FindWord find = new FindWord();
// Text to search if a word is contained
String text = "This is a simple text to search for a word";
// Calling the method to search for a word in the text above
find.searchFor("simple", text);
}
}
public class FindWord {
public void searchFor(String word, String text){
// Add every word of text in a list
String string[] = text.split(" ");
for (int i=0; i<string.length; i++){
// if the word is in the list then print the word and the position where it is
if (word.equals(string[i])) {
System.out.println("The word " + word + " found at position " + i + " of text");
}
}
}
}
评论
0赞
Matthew Grathwol
11/28/2022
#2
软件包例外;
导入 java.util.Scanner;
公共类聊天机器人 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String [] keywords = {"Bad", "Good", "Great", "Sad"};
System.out.println("How are you feeling today?");
String response = input.nextLine();
// [I] [am] [doing] [good]
String [] responseArray = response.split(" ");
for (int i = 0; i < responseArray.length; i++) {
String word = responseArray[i];
for(int j = 0; j < keywords.length; j++){
if(word.equalsIgnoreCase(keywords[j])){
String matchedKeyword = keywords[j];
if(matchedKeyword.equalsIgnoreCase("good")
|| matchedKeyword.equalsIgnoreCase("great")){
System.out.println("Super! Happy for you!");
}
if(matchedKeyword.equalsIgnoreCase("bad")
|| matchedKeyword.equalsIgnoreCase("sad")){
System.out.println("I'm sorry, hope you feel better soon!");
}
}
}
}
}
}
评论