java – chatbot: not be able to apply to keep code take the input until i want it to terminate

It would be something like this:

public static main(String[] args) {
    System.out.println("Welcome to the CHATBOTn");
    Scanner sc = new Scanner(System.in);

    String g = "";
    while (g.isEmpty()) {
        System.out.print("> ");
        String g = sc.nextLine();
        processInput(g);
        g = ""; // empty g so to keep looping;    
    }
}

private void processInput(String g) {
    String s = g.toUpperCase();
    if (s.contains("HI")) {
        System.out.println("Hello");
    } else if (s.contains("HOW ARE")) {
         System.out.println("i am goodn what about u");
    } else if (s.contains("I AM GOOD")) {
        System.out.println("okay thats nicen so now what");
    } else if (s.contains("NAME")) {
        System.out.println("i am a chat bot i talk with peoplesn and whatS youRS");
    } else {
        System.out.println("i did not Understand, What you Said!");
    }
}

On a side:

I don’t think that hard-coding your User and Bot responses is a good idea. It would be better to pull that information from a Text file, that way you can have almost an unlimited number of response types you like. Just as an example, here is a custom response data file, let’s say the file is named BotTalk.txt:

[I need help ~ help me ~ help]
What do you need help with?

[Hi ~ hello ~ anyone there ~ ola ~ Hi there ~ hello there]
Hello. ~ Hello how are you? ~ Hello, how can I help you?

[How are you]
I am good, how about you?

[I am good ~ I'm good ~ I am doing great ~ I'm doing great ~ I am fine ~ I'm great]
Okay, thats nice. How can I help you?
       
[What is your name ~ Your name]
I am a Chat Bot and I talk to people. What is your name?

[What time is it ~ What is the time ~ Give me the time ~ the time]
Well, the current time here is %time%.

[What is the date ~ what is the current date ~ the date]
Well, the date here is (MM-DD-YYYY): %date%.

[quit ~ close ~ exit ~ byebye ~ bye bye ~ bye]
Well, thanks for chatting and I'll Talk to you later. Bye Bye.%quit%

In this file you can see tilde (~) delimited strings enclosed in Square Brackets ( [ ] ). The tilde delimited string within these brackets would be possible User input strings to handle. Let’s take the first one: [I need help ~ help me ~ help]. If the User enters I need help or Help me or help (not letter case sensitive) then the Bot response to any one of those User inputs would be the next file line following the User input file line. If the Bot Response file line contains several Title (~) delimited strings then the app would respond randomly with any one of those particular Bot Responses on that file line. In this particular case, there is only one Bot Response: What do you need help with? and that is what the bot would respond with.

You will also notice within the text file data that there are custom tags like %time%, %date%and %quit%. All file lines processed for a Bot Response are checked for these custom tags and the appropriate replacement is applied. This shows you how you can apply your own custom tags within the file. The processTags() method within the runnable would take care of these tags whichever way you like.

Provided is a runnable application you can play with which demonstrates how this works. Create a new project and use the provided runnable code below into it. Now, copy the file text provided above and past it into a new text file and save it into the Project folder of your application. Run the application. Enter Hi or hi or hello several times at the User prompt ( > ) to see the different possible Bot Responses available in file. You will see how they can be different every time hi is supplied.

Here is the runnable:

public class ChatBotDemo {
    public final String LS = System.lineSeparator();
    public final java.util.Scanner sc = new java.util.Scanner(System.in);

    private boolean quitRequested = false;
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // App started this way to avoid the need for statics.
        new ChatBotDemo().startApp(args);
    }
    
    private void startApp(String[] args) {
        System.out.println("Welcome to the CHATBOT" + LS);
        String userInput = "";
        while (userInput.isEmpty()) {
            System.out.print("> ");
            userInput = sc.nextLine();
            botProcess(userInput);
            /* Empty userInput so to keep looping until "quit", "close", "exit", 
               "bye", "byebye", or "bye bye" is Entered at which point the app
               displays the message contained within the BotTalk.txt for any one
               of those specific entries and then closes.                 */
            userInput = "";  
        }
    }
    
    public void botProcess(String input) {
        String ls = System.lineSeparator();
        
        java.io.File botTalkFile = new java.io.File("BotTalk.txt");
        boolean userResponseFound = false;
        
        // 'Try With Resouces' used here to auto-close the reader and free resources.
        try (java.util.Scanner reader = new java.util.Scanner(botTalkFile)) {
            String line;
            while (reader.hasNextLine()) {
                line = reader.nextLine().trim();
                //Skip blank lines (if any)
                if (line.isEmpty()) { continue; }
                
                if (line.startsWith("[") && line.endsWith("]")) {
                    line = line.substring(1, line.length() - 1);
                    String[] userResponse = line.split("\s*~\s*");
                    
                    for (String userResp : userResponse) {
                        if (userResp.equalsIgnoreCase(input) || input.toLowerCase().startsWith(userResp.toLowerCase()) 
                                                             || userResp.toLowerCase().startsWith(input.toLowerCase())) {
                            userResponseFound = true;
                            String botResponses = reader.nextLine().trim();
                            if (botResponses.isEmpty()) { 
                                System.out.println("Failed Bot Response!" + ls);
                                break; 
                            }
                            else {
                                String[] botResp = botResponses.split("\s*~\s*");
                                String response = botResp[new java.util.Random().nextInt(botResp.length)];
                                response = processTags(response);
                                System.out.println(response + ls);
                                if (quitRequested) {
                                    System.exit(0);
                                }
                            }
                            break;
                        }
                    }
                }
                if (userResponseFound) {
                    break;
                }
            }
        }
        catch (java.io.FileNotFoundException ex) {
            System.err.println(ex.getMessage());
        }
        if (!userResponseFound) {
            System.out.println("I'm sorry, I did not understand, what you said!" + ls);
        }
    }
    
    private String processTags(String response) {
        response = response.replace("%time%", java.time.LocalTime.now().format(java.time.format
                                               .DateTimeFormatter.ofPattern("hh:mm a")));
        response = response.replace("%date%", java.time.LocalDate.now()
                           .format(java.time.format.DateTimeFormatter.ofPattern("MM-dd-uuuu")));
        if (response.toLowerCase().contains("%quit%")) {
            response = response.replace("%quit%", "");
            quitRequested = true;
        }
        
        return response;
    }
    
}

Leave a Comment