有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

简单的java AI响应程序?

嗨,我有这个节目:

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");
            }
        }

    }
}

它适用于前两个回答,如果输入其他内容,它会打印“对不起,我没听清楚你做得好还是坏?”没错,但我希望它在打印后再次收到回复。在它说“对不起,我没听清楚你做得好还是坏?”它不允许你输入任何其他内容


共 (3) 个答案

  1. # 1 楼答案

    只要使用无限循环。像这样的

    while(true){
    
      // your code here...
    
      if(input.equals("exit")) break; 
    
    }
    

    这是最简单的解决方案

  2. # 2 楼答案

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

    你应该替换

    System.out.print("Sorry I didn't catch that are you doing good or bad?");
    

    System.out.println("Sorry I didn't catch that are you doing good or bad?");
    

    这样你就可以在实际输入之前进入下一行。希望这有帮助

  3. # 3 楼答案

    可以通过添加while循环来实现这一点

    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?");
            }
          }
        }
    }