-1

I am tasked to create a simple chatbot that enables a user to create questions and answers, which will then be stored into two arrays. Hence, whenever the user input the same question, the chatbot will be able to print out the answer.

For example, My intended run is: Bot: 1st question that you want to create. User: What is my name? Bot: and the response is? user: Tom Bot: 2nd question that you want to create. user: How tall am I? Bot: and the response is? You: 179cm You: How tall am I? Bot: 179cm You: What is my name? Bot: Tom

Below is my source code:

public static void main(String[] args) {

       String reply = "";
       String[] storeQuestions = new String [100];
       String[] storeAnswers = new String [100];

       do { 
            /* first question*/
            System.out.println("Bot: 1st question that you want to create.");
            Scanner input = new Scanner (System.in);
            System.out.print("You: ");
            String createQuestion = input.nextLine(); // change to string
            System.out.println("Bot: and the response is?");
            System.out.print("You: ");
            String answer = input.nextLine();

            /* storing question and answer into the two arrays */
            storeQuestions[0] = createQuestion;
            storeAnswers[0] = answer;

            /* second question */
            System.out.println("Bot: 2nd question that you want to create.");
            System.out.print("You: ");
            createQuestion = input.nextLine();
            System.out.println("Bot: and the response is?");
            System.out.print("You: ");
            answer = input.nextLine();

            storeQuestions[1]= createQuestion;
            storeAnswers[1] = answer;
            System.out.print("You: ");
            reply = input.nextLine();

            if(storeQuestions[0]==createQuestion) {
                System.out.println("Bot: "+storeAnswers[0]);
            }
            else if ( storeQuestions[1]==createQuestion) {
                System.out.println("Bot: "+storeAnswers[1]);
            }
        }while(reply!="bye");               
}    

}

XxS0ul678
  • 117
  • 1
  • 15
  • 1
    use `equals(String another)` to compare strings. Other than that, It's also not clear what the problem you're facing is. – Ousmane D. Jul 15 '17 at 19:11

1 Answers1

-1

The == operator compares the hash codes of the two objects. Since they might not be the same for two strings (even though, they are identical) you have to check character by character. A built-in method that can do this for you is String.equals(). If upper and lower case doesn't matter, you'd use String.equalsIgnoreCase().

Examples:

"test".equals("test")            true
"TEST".equals("test")            false
"TEST".equalsIgnoreCase("test")  true
eliaspr
  • 302
  • 3
  • 15