How do you pick a word from a string or scanner input, say for instance a search engine search?
I looked up indexOf() for a string but I’m not finding how to make a public void word class from finding a word from a line of text. Hoping every word can be a variable.
CodePudding user response:
From what you asked this is what I understood. Main class with a new FindWord object, a text and the method of the object. Class named FindWord with a method called searchFor() with two parameters. The first parameter is the word you want to find and the second parameter is the text you want to be searched.
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");
}
}
}
}
CodePudding user response:
package exceptions;
import java.util.Scanner;
public class ChatBot {
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!");
}
}
}
}
}
}