首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简单的java AI响应程序?

简单的java AI响应程序?
EN

Stack Overflow用户
提问于 2014-06-25 11:11:45
回答 3查看 661关注 0票数 0

嗨,我有个节目:

代码语言:javascript
复制
import java.util.Scanner;

public class HowAreYou {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input;

        System.out.println("How are you?");
        input = in.nextLine();
        if (input.equals("I'm doing good!")) {
            System.out.print("That's great to hear!");
        } else if (input.equals("I'm not doing too well...")) {
            System.out.print("Aw I'm sorry to hear that");
        } else {
            System.out.print("Sorry I didn't catch that are you doing good or bad?");
            input = in.nextLine();
            if (input.equals("good")) {
                System.out.print("That's great to hear!");
            } else if (input.equals("bad")) {
                System.out.print("Aw I'm sorry to hear that");
            }
        }

    }
}

它对前两个响应很好,如果您输入了其他内容,它会打印“对不起,我没注意到,您做得好还是坏?”正确,但我希望它在打印后再次得到响应。这时,它说:“对不起,我没听清楚,你做得好还是坏?”它不允许你输入任何其他东西。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-06-25 11:30:37

我认为您面临的问题是,在"Sorry I didn't catch that are you doing good or bad?"消息之后,您点击enter key来给出响应,您的程序就会终止。之所以会发生这种情况,是因为input.nextLine消耗了它,并且它与任何东西都不匹配,并且程序退出。

你应该换掉

代码语言:javascript
复制
System.out.print("Sorry I didn't catch that are you doing good or bad?");

使用

代码语言:javascript
复制
System.out.println("Sorry I didn't catch that are you doing good or bad?");

以便在实际输入之前到达下一行。希望这能有所帮助。

票数 0
EN

Stack Overflow用户

发布于 2014-06-25 11:18:02

只要使用无限循环即可。就像这样

代码语言:javascript
复制
while(true){

  // your code here...

  if(input.equals("exit")) break; 

}

这是最简单的解决办法。

票数 2
EN

Stack Overflow用户

发布于 2014-06-25 11:20:58

您可以通过添加一个while循环来完成这一任务。

代码语言:javascript
复制
import java.util.Scanner;

public class HowAreYou {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String input;

        /* loop which keeps asking for input  ends when user enters Bye Bye*/
        while(true){ 

        System.out.println("How are you?");
        input = in.nextLine();
        if (input.equals("I'm doing good!")) {
            System.out.println("That's great to hear!");
            break;
        } else if (input.equals("I'm not doing too well...")) {
            System.out.println("Aw I'm sorry to hear that");
            break;
        } else if (input.equals("Bye Bye")) {
            System.out.println("Bye Bye");
            break;
        } else {
            System.out.println("Sorry I didn't catch that are you doing good or bad?");
        }
      }
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24407094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档