有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查字符串中的单词是否在数组中

我正在制作一个聊天机器人,我想让它检查您键入的任何单词是否与预定义列表中的单词匹配

例如:我键入I'm good thanks!
我有一个带有awesomeperfecthappygood的列表
我希望程序检查I'mgoodthanks!是否在列表中

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import use.*;

public class welcome {


public static void say() {


}

public static void main(String[] args) {
    wait.clean();
    String input1 = "";
    String name = "Antonio";
    String surname = "Solana";
    Scanner scanner1 = new Scanner(System.in);
    String[] goodadj = {"good", "well", "awesome", "perfect", "adaptable", "adventurous", "affable", "affectionate", "agreeable", "ambitious", "amiable", "amicable", "amusing", "brave", "bright", "broad-minded", "calm", "careful", "charming", "communicative", "compassionate", "conscientious", "considerate", "convivial", "courageous", "courteous", "creative", "decisive", "determined", "diligent", "diplomatic", "discreet", "dynamic", "easygoing", "emotional", "energetic", "enthusiastic", "exuberant", "fair-minded", "faithful", "fearless", "forceful", "frank", "friendly", "funny", "generous", "gentle", "good", "gregarious", "hard-working", "happy", "helpful",  "honest", "humorous", "imaginative", "impartial", "independent", "intellectual", "intelligent", "intuitive", "inventive", "kind", "loving", "loyal", "modest", "neat", "nice", "optimistic", "passionate", "patient", "persistent", "pioneering", "philosophical", "placid", "plucky", "polite", "powerful", "practical", "pro-active", "quick-witted", "quiet", "rational", "reliable", "reserved", "resourceful", "romantic", "self-confident", "self-disciplined", "sensible", "sensitive", "shy", "sincere", "sociable", "straightforward", "sympathetic", "thoughtful", "tidy", "tough", "unassuming", "understanding", "versatile", "warmhearted", "willing", "witty"};
    String[] badadj = {"awful", "sad", "bad", "aggressive", "aloof", "arrogant", "belligerent", "big-headed", "bitchy", "boastful", "bone-idle", "boring", "bossy", "callous", "cantankerous", "careless", "changeable", "clinging", "compulsive", "conservative", "cowardly", "cruel", "cunning", "cynical", "deceitful", "detached", "dishonest", "dogmatic", "domineering", "finicky", "flirtatious", "foolish", "foolhardy", "fussy", "greedy", "grumpy", "gullible", "harsh", "impatient", "impolite", "impulsive", "inconsiderate", "inconsistent", "indecisive", "indiscreet", "inflexible", "interfering", "intolerant", "irresponsible", "jealous", "lazy", "Machiavellian", "materialistic", "mean",  "miserly", "moody", "narrow-minded", "nasty", "naughty", "nervous", "obsessive", "obstinate", "overcritical", "overemotional", "parsimonious", "patronizing", "perverse", "pessimistic", "pompous", "possessive", "pusillanimous", "quarrelsome", "quick-tempered", "resentful", "rude", "ruthless", "sarcastic", "secretive", "selfish", "self-centred", "self-indulgent", "silly","sneaky", "stingy", "stubborn", "stupid", "superficial", "tactless", "timid", "touchy", "thoughtless", "truculent", "unkind", "unpredictable", "unreliable", "untidy", "untrustworthy", "vague", "vain", "vengeful", "vulgar", "weak-willed"};
    String[] afirmation = {"ok", "okay", "yes", "well", "affirmative", "amen", "fine", "good", "okay", "true", "yeah", "all right", "aye", "beyond a doubt", "by all means", "certainly", "definitely", "even so", "exactly", "gladly", "good enough", "granted", "indubitably", "just so", "most assuredly", "naturally", "of course", "positively", "precisely", "sure thing", "surely", "undoubtedly", "unquestionably ", "very well", "willingly", "without fail", "yep star"};
    String[] negation = {"no", "nope", "never", "nix", "absolutely not", "not at all", "no way", "by no means", "not by any means"};

    Random rand = new Random();

    int x = rand.nextInt((6 - 1) + 1) + 1;
    String hi = "";
    if (x == 1) {
        hi = "Hey! Sup ";
    }

    if (x == 2) {
        hi = "Nice to see you again ";
    }

    if (x == 3) {
        hi = "You smell good today ";
    }

    if (x == 4) {
        hi = "Kon'nichiwa ";
    }

    if (x == 5) {
        hi = "I didn't heard you comming ";
    }

    if (x == 6) {
        hi = "Wasssaaap ";
    }

    x = rand.nextInt((6 - 1) + 1) + 1;
    String question1 = "";
    if (x == 1) {
        question1 = "How are you today boy?";
    }

    if (x == 2) {
        question1 = "U good?";
    }

    if (x == 3) {
        question1 = "You look good don't you? (I can't see you... sorry...)";
    }

    if (x == 4) {
        question1 = "How are you feeling?";
    }

    if (x == 5) {
        question1 = "How are you this beautiful day?";
    }

    if (x == 6) {
        question1 = "Was your day good?";
    }

    x = rand.nextInt((6 - 1) + 1) + 1;
    String joke = "";
    if (x == 1) {
        joke = "What's the difference between snowmen and snowladies? Snowballs.";
    }

    if (x == 2) {
        joke = "I am a nobody, nobody is perfect, therefore I am perfect.";
    }

    if (x == 3) {
        joke = "Siri. You should laugh, she is a joke.";
    }

    if (x == 4) {
        joke = "Do you know the dentist who never agrees with the other nine? I think he is sleeping or something.";
    }

    if (x == 5) {
        joke = "Why do farts smell? So deaf people can enjoy them too.";
    }

    if (x == 6) {
        joke = "I asked God for a bike, but I know God doesn't work that way. So I stole a bike and asked for forgiveness.";
    }

    x = rand.nextInt((6 - 1) + 1) + 1;
    String happy = "";
    if (x == 1) {
        happy = "What's the difference between snowmen and snowladies? Snowballs.";
    }

    if (x == 2) {
        happy = "I am a nobody, nobody is perfect, therefore I am perfect.";
    }

    if (x == 3) {
        happy = "Siri. You should laugh, she is a joke.";
    }

    if (x == 4) {
        happy = "Do you know the dentist who never agrees with the other nine? I think he is sleeping or something.";
    }

    if (x == 5) {
        happy = "Why do farts smell? So deaf people can enjoy them too.";
    }

    if (x == 6) {
        happy = "I asked God for a bike, but I know God doesn't work that way. So I stole a bike and asked for forgiveness.";
    }

    x = rand.nextInt((6 - 1) + 1) + 1;
    String sad = "";
    if (x == 1) {
        sad = "What's the difference between snowmen and snowladies? Snowballs.";
    }

    if (x == 2) {
        sad = "I am a nobody, nobody is perfect, therefore I am perfect.";
    }

    if (x == 3) {
        sad = "Siri. You should laugh, she is a joke.";
    }

    if (x == 4) {
        sad = "Do you know the dentist who never agrees with the other nine? I think he is sleeping or something.";
    }

    if (x == 5) {
        sad = "Why do farts smell? So deaf people can enjoy them too.";
    }

    if (x == 6) {
        sad = "I asked God for a bike, but I know God doesn't work that way. So I stole a bike and asked for forgiveness.";
    }



    System.out.println(hi + name);
    wait.one();
    System.out.println(question1);
    input1 = scanner1.next();
    input1 = input1.toLowerCase();
    String[] input2 = input1.split(" ");

    if (Arrays.asList(goodadj).contains(input2) || Arrays.asList(afirmation).contains(input2)) {
        System.out.println("Good for you!");
        wait.one();
        System.out.println("Do you want to tell me about it?");
        input1 = scanner1.next();
        input1 = input1.toLowerCase();
        input2 = input1.split(" ");

        if (Arrays.asList(goodadj).contains(input2) || Arrays.asList(afirmation).contains(input2)) {
            input1 = scanner1.next();
            System.out.println(happy);
        }

        if (Arrays.asList(goodadj).contains(input2) || Arrays.asList(afirmation).contains(input2)) {
            input1 = scanner1.next();
            System.out.println(sad);
        }

    }

    if (Arrays.asList(badadj).contains(input2) || Arrays.asList(negation).contains(input2)) {
        System.out.println("I'm sorry, I could help you if you want...");
        input1 = scanner1.next();
        input1 = input1.toLowerCase();

        if (Arrays.asList(afirmation).contains(input2)) {
            System.out.println(joke);
        }

        if (Arrays.asList(negation).contains(input2)) {
            System.out.println("I understand");
        }
    }

    else {
        System.out.println("I don't really understand that...");
    }


}

} 这就是我所尝试的goodadj是我要搜索的列表,good是该列表中的输入词。 我被允许使用任何我想要的,这个项目只是为了好玩。感谢所有帮助我的人


共 (3) 个答案

  1. # 1 楼答案

    /** Will return a set of words which are in the array and the sentence. */
    public Set<String> checkWords( String sentence, String[] words )
    {
      Set<String> result = new HashSet<>()
      String[] wordsInSentence = sentence.split(" ");
      for( String word : wordsInSentence )
      {
        for( String word2 : words )
        {
          if ( word.equals(word2) )
          {
            result.add( word );
            break;
          }
        }
      }
    }
    

    不过,如果使用集合而不是数组,效果会更好。它能更好地表达意思,使用哈希集会更有效

    /** Will return a set of words which are in the set and the sentence. */
    public Set<String> checkWords( String sentence, Set<String> words )
    {
      Set<String> result = new HashSet<>()
      String[] wordsInSentence = sentence.split(" ");
      for( String word : wordsInSentence )
      {
        if ( words.contains(word) )
          result.add( word );
      }
    }
    
  2. # 2 楼答案

    您应该用空格“,”和“,”等分隔符分隔输入。。。数组中的所有单词都应该移动到一个集合中(最好是HashSet),并与

    if (wordSet.contains(wordToCheck)) { doSomething(); }
    

    您可以将所有输入单词和集合中的单词转换为小写或大写,以匹配“good”、“good”、“good”

  3. # 3 楼答案

    使用将输入值存储到数组中。拆分(“”)

    String [] baseValues = {"Awesome", "Perfect", "Happy", "Good"};
    
    Scanner scan = new Scanner();
    
    String userInput = scan.nextLine();
    
    String [] inputArray = userInput.split(" ");
    

    这给了你类似的东西[“我,m”,“很好”,“谢谢!”]

    对于inputArray的每个值,循环这些值并将其与每个基值进行比较

    获取输入的用户的输入,循环遍历数组中的值,查看它们提供给您的字符串是否正确。包含它们中的任何一个

    **免责声明,这些是低效的,使用哈希集将是最佳方式,这些响应特定于数组