【发布时间】:2014-04-12 23:40:14
【问题描述】:
所以我尝试使用 if 语句检查字符串,我创建了一个测试计算机,它根据输入给出预定的响应,唯一有效的输入恰好是 hi 或 hello,带空格的字符串似乎没有工作,这是为什么呢?
import java.util.Scanner;
public class ComputaBot {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String text;
String computer = "ComputaBot:";
String[] input = {
"how are you?", "hi", "hello", "what is your name",
"do you like chicken?", "where are you from?",
"do you like cheese?"
};
do{
System.out.println("Type to talk!:");
text = scan.next();
if (text.equals(input[1]) || text.equals(input[2])) {
System.out.println(computer + " " +"Hello!");
}else if (text.equalsIgnoreCase(input[0])) {
System.out.println(computer + " " +"I'm fine, you?!");
}else if (text.equals(input[3])) {
System.out.println(computer + " " +"Jimmy");
}else if (text.equals(input[4])) {
System.out.println(computer + " " +"Yes! Love it");
}else if (text.equals(input[5])){
System.out.println(computer + " " +"Germany");
}else if (text.equals(input[6])){
System.out.println(computer + " " +"only on pizza");
}else
System.out.println("bye");
}while(!text.equals("bye"));
scan.close();
}
}
【问题讨论】:
-
因为
scan.next()只能得到一个字。
标签: java string if-statement