You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Java程序在回答3个问题后自动终止?

解决方案

要实现程序在用户提问3次后自动终止,只需添加计数器统计提问次数,同时保留输入Bye提前终止的功能。以下是修改后的完整代码:

import java.util.Scanner;
    
class Bot {
    public static void main(String[] args) {
        System.out.println("QUESTIONS: How old are you? | What is your name? | What did you eat for breakfast?");
        System.out.println("Ask a question?");
    
        Scanner pytania = new Scanner(System.in);
        String input;
        
        boolean running = true;
        int questionCount = 0; // 新增计数器,统计提问次数
        while (running && questionCount < 3) { // 循环条件:程序运行中且提问次数未达3次
            System.out.println(" ");
            input = pytania.nextLine();
    
            if (input.equals("How old are you?")) {
                System.out.println("I am 125 years old");
            } else if (input.equals("Bye")) {
                System.out.println("Bye!");
                running = false; // 输入Bye直接终止程序
            } else if (input.equals("What is your name?")) {
                System.out.println("My name is Christopher");
            } else if (input.equals("What did you eat for breakfast?")) {
                System.out.println("I had scrambled eggs for breakfast");
            } else {
                System.out.println("Sorry, I don't understand the question!");
            }
            
            if (running) { // 未提前终止时,计数器加1
                questionCount++;
                if (questionCount == 3) {
                    System.out.println("已回答3个问题,程序结束!");
                    running = false;
                }
            }
        }
        pytania.close(); // 关闭输入流,规范资源管理
    }
}

关键修改说明:

  • 新增questionCount变量,初始值为0,用于记录用户提问次数
  • 修改while循环条件,仅当程序处于运行状态且提问次数小于3时,继续执行循环
  • 每次处理完用户输入(未提前输入Bye)后,计数器自增1
  • 当计数器达到3时,输出结束提示并终止程序
  • 添加pytania.close()关闭Scanner,避免资源泄漏

修改后程序既会在用户提问3次后自动终止,也保留了输入Bye提前结束的功能。

内容的提问来源于stack exchange,提问作者mrspjsh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:20:27