我在制作 java 聊天机器人程序时需要帮助,但我无法让该程序将用户输入与存储的字符串进行比较
I need help in making a java chatbot program but I cannot get the program to compare the user input to the stored string
这是我使用的字符串
String [] hi = {"hello","hi","whats up"};
我希望程序在每次用户键入时显示字符串中的一个单词"hi",但我的代码无法比较用户输入和字符串
do{
System.out.println("You:");
s.next();
String[] userinput={"hi"};
if(userinput.equals("hi")){
Random r = new Random();
rno = r.nextInt(3);
System.out.println("bot:"+hi[rno]);
}
else{
System.out.println("Bot:Bye");
}
}while(true);
请帮忙
您将一个字符串数组与一个字符串进行比较。由于类型不同,这将始终 return false。
相反,您可以使用集合的 contains
方法。示例:
List<String> userInput = Arrays.asList("hi");
if (userInput.contains("hi")) {
//Do something
}
userinput is String[], 你需要比较String as
userinput[0].equals("hi")
userinput 永远不会等于 "hi" 因为 "hi" 是一个 String 对象,而 userinput 是一个 String[](字符串数组)对象。
如果 userinput 应该是一个数组(一堆字符串),那么您需要通过执行以下操作进行比较:
for(String s:userinput){
if(s.equals("Hi")){
//do whatever you want to do when this happens
}
}
如果用户输入总是一个字符串,那么你应该说
String userinput = "Hi";
改用地图
Map<String,String>map=new HashMap<String,String>();
map.put("Hello","Hi");
System.out.println(map.get(s.next()).toString());
您正在将字符串数组与字符串进行比较。尝试 userInput[0].equals("hi")
这是我使用的字符串
String [] hi = {"hello","hi","whats up"};
我希望程序在每次用户键入时显示字符串中的一个单词"hi",但我的代码无法比较用户输入和字符串
do{
System.out.println("You:");
s.next();
String[] userinput={"hi"};
if(userinput.equals("hi")){
Random r = new Random();
rno = r.nextInt(3);
System.out.println("bot:"+hi[rno]);
}
else{
System.out.println("Bot:Bye");
}
}while(true);
请帮忙
您将一个字符串数组与一个字符串进行比较。由于类型不同,这将始终 return false。
相反,您可以使用集合的 contains
方法。示例:
List<String> userInput = Arrays.asList("hi");
if (userInput.contains("hi")) {
//Do something
}
userinput is String[], 你需要比较String as
userinput[0].equals("hi")
userinput 永远不会等于 "hi" 因为 "hi" 是一个 String 对象,而 userinput 是一个 String[](字符串数组)对象。
如果 userinput 应该是一个数组(一堆字符串),那么您需要通过执行以下操作进行比较:
for(String s:userinput){
if(s.equals("Hi")){
//do whatever you want to do when this happens
}
}
如果用户输入总是一个字符串,那么你应该说
String userinput = "Hi";
改用地图
Map<String,String>map=new HashMap<String,String>();
map.put("Hello","Hi");
System.out.println(map.get(s.next()).toString());
您正在将字符串数组与字符串进行比较。尝试 userInput[0].equals("hi")