如何将基于if-else的聊天机器人改为用数组扫描用户输入的版本?
Convert Your JOptionPane Chatbot to Use Arrays
Got it, let's break this down—arrays are just ordered lists of items, perfect for grouping your keywords and their matching responses instead of writing endless if-else statements. Here's how to refactor your code step by step:
Step 1: Understand the Array Basics
We'll use two arrays:
- One to store all your keywords (e.g., "hello", "how are you")
- Another to store the corresponding responses (the message you want to show for each keyword)
The index position of each keyword matches the index of its response (so keywords[0] pairs with responses[0], etc.).
Step 2: Full Refactored Code
import javax.swing.JOptionPane; public class SimpleChatBot { public static void main(String[] args) { // 1. Create arrays for keywords and their matching responses String[] keywords = {"hello", "how are you", "goodbye", "thanks", "help"}; String[] responses = { "Hi there! 😊", "I'm doing well, thanks for asking!", "See you soon—have a great day!", "You're very welcome!", "I can help with basic questions like greetings or saying goodbye!" }; // 2. Get user input (convert to lowercase to make matching case-insensitive) String userInput = JOptionPane.showInputDialog("Type your message:").toLowerCase(); boolean keywordFound = false; // 3. Loop through the keywords array to check for matches for (int i = 0; i < keywords.length; i++) { if (userInput.contains(keywords[i])) { JOptionPane.showMessageDialog(null, responses[i]); keywordFound = true; break; // Exit the loop once we find a matching keyword } } // 4. If no keyword was found, show a default message if (!keywordFound) { JOptionPane.showMessageDialog(null, "Sorry, I don't understand that yet. Try asking something simple!"); } } }
Key Explanations:
- Arrays:
keywordsandresponsesare bothStringarrays. Each keyword at positionihas its response at the sameiin the responses array. - Loop: The
forloop goes through every keyword in the array. If the user's input contains the keyword, we show the matching response and stop looping. - Case Insensitivity:
toLowerCase()ensures the bot matches "Hello", "HELLO", or "hello" without extra code. - Scalability: Adding new keywords/responses is easy—just add a new entry to both arrays (make sure they stay in the same order!).
How to Expand This:
Want to add more interactions? Just append to the arrays:
// Add new keyword and response String[] keywords = {"hello", "how are you", "goodbye", "thanks", "help", "what time is it"}; String[] responses = { "Hi there! 😊", "I'm doing well, thanks for asking!", "See you soon—have a great day!", "You're very welcome!", "I can help with basic questions like greetings or saying goodbye!", "I don't have a clock, but you can check your device's time!" };
内容的提问来源于stack exchange,提问作者Huseyin Yesiler
相关产品推荐
相关产品推荐

