我想比较字符串,但它没有识别

时间:2014-03-10 01:12:27

标签: java string if-statement

所以我试图使用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();
}
 }

3 个答案:

答案 0 :(得分:4)

方法next()读取一个单词。您应该使用的是nextLine(),它读取整行(按 Enter 时输入的换行符分隔):

text = scan.nextLine();

来自JavaDocs

  

public String next():查找并返回此扫描程序中的下一个完整令牌。完整的标记之前和之后是与分隔符模式匹配的输入。

答案 1 :(得分:3)

使用

scan.nextLine() 

而不是

scan.next()

答案 2 :(得分:0)

Scan.next()只读取下一个单词,你想要scan.nextLine()作为整行。如果你使用Map添加所有问题/答案作为一对会更好,这样你就不必做所有if / then / else语句。

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class ComputaBot {

   public ComputaBot() {
   }

   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      String text;
      String computer = "ComputaBot:";
      Map<String,String> bot = new HashMap<String,String>();
      bot.put("how are you?", "I'm fine, you?!");
      bot.put("how are you?", "Hello!");
      bot.put("hi", "Hello!");
      bot.put("what is your name", "Jimmy");
      bot.put("do you like chicken?", "Yes! Love it");
      bot.put("where are you from?", "Germany");
      bot.put("do you like cheese?", "only on pizza");

      do {
         System.out.println("Type to talk!:");
         text = scan.nextLine();

         String answer = bot.get(text.toLowerCase());
         System.out.println(computer + " " + answer);
      } while (!text.equalsIgnoreCase("bye"));
      scan.close();
   }
}