人工不智能问答小程序
- 目的是为了学习面向对象编程,熟悉模块化编程思维
人工智障问答小程序
1. AI包
1. ai模块
package AI;
public class ai {
/**
* 公共类,面向用户可以操作的类
* 用于用户输入并返回结果
* @param question 获取用户字符串输入
* @return返回对应处理后的回答结果
*/
public String answer(String question) {
String ret = null;
ret = handleCanStart(question);
if (ret != null) {
return ret;
}
ret = handleAskTail(question);
if (ret != null) {
return ret;
}
return handleUnknow(question);
}
/**
* 私有类,拒绝提供给用户直接修改的机会
* 对开头匹配输入进行回答处理
* @param question 获取用户输入
* @return返回开头匹配回答结果
*/
private String handleCanStart(String question) {
String[] canStart = new String[]{"会", "能", "有", "敢", "在"};
for (int i = 0; i < canStart.length; i++) {
if (question.startsWith(canStart[i])) {
return canStart[i] + "!";
}
}
return null;
}
/**
* 私有类,拒绝提供给用户直接修改的机会
* 对结尾匹配输入进行回答处理
* @param question 获取用户输入
* @return返回结尾匹配回答结果
*/
private String handleAskTail(String question) {
String[] askTail = new String[]{"吗?", "吗?", "吗"};
for (int i = 0; i < askTail.length; i++) {
if (question.endsWith(askTail[i])) {
return question.replace(askTail[i], "!");
}
}
return null;
}
/**
* 私有类,拒绝提供给用户直接修改的机会
* 对无匹配匹配输入进行回答处理
* @param question 获取用户输入
* @return返回无匹配回答结果
*/
private String handleUnknow(String question) {
return question + "!";
}
}
分割功能,将用户和私有的模块分开
2. 主程序
import AI.ai;
import java.util.Scanner;
public class AIAPP {
public static void main(String[] args) {
ai ai = new ai();
Scanner scanner = new Scanner(System.in);
while (true){
String input = scanner.next();
if("exit".equals(input)){
System.out.println("再见!");
break;
}
System.out.println(ai.answer(input));
}
}
}
总结
String.startWith
boolean startsWith(String prefix)
Tests if this string starts with the specified prefix
boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with thespecified prefix.
String.replace
String replace(char oldChar, char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String.endsWith
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
String.equals
boolean equals(Object anObject)
Compares this string to the specified object.
官方Javadoc地址: https://docs.oracle.com/en/java/javase/11/docs/api/index.html