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

Java循环实现:如何让程序未满足if/else if条件时重复执行

实现Java程序的循环询问逻辑

嘿,我懂你现在的困惑啦!你需要给程序加个循环结构,让它在用户输入不符合if/else if判定条件的时候反复询问“how are you”对吧?这里最适合用do-while循环,因为它会先执行一次提问逻辑,再判断是否需要继续循环,完美匹配你的需求。

我给你修改后的示例代码,你可以根据自己的实际判定条件调整:

import java.util.Scanner;

public class HowAreYouProgram {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String userInput;
        
        do {
            // 先执行一次提问和输入获取
            System.out.println("how are you");
            userInput = scanner.nextLine();
            
            // 这里替换成你自己的if和else if判定逻辑
            if (userInput.equalsIgnoreCase("great")) {
                System.out.println("Awesome to hear that!");
            } else if (userInput.equalsIgnoreCase("not so good")) {
                System.out.println("Hope things get better soon!");
            }
            // 如果输入不满足上面的条件,循环会自动重复
        } while (!(userInput.equalsIgnoreCase("great") || userInput.equalsIgnoreCase("not so good")));
        
        scanner.close();
    }
}

代码解释:

  • do代码块:负责执行提问和输入读取,不管条件如何都会先运行一次,确保用户第一次能看到问题。
  • while后的判断条件:这里用了逻辑非!,意思是当输入既不是"great"也不是"not so good"时,循环继续执行。你只需要把括号里的条件替换成你自己的if/else if判定条件的组合就行——也就是当输入不满足你想要的条件时,这个表达式为true,程序就会回到开头重新提问。

如果你更习惯用while循环,也可以这样写(需要先给输入变量赋初始值):

import java.util.Scanner;

public class HowAreYouProgram {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String userInput = ""; // 初始化输入变量
        
        // 先判断条件,再执行循环内容
        while (!(userInput.equalsIgnoreCase("great") || userInput.equalsIgnoreCase("not so good"))) {
            System.out.println("how are you");
            userInput = scanner.nextLine();
            
            if (userInput.equalsIgnoreCase("great")) {
                System.out.println("Awesome to hear that!");
            } else if (userInput.equalsIgnoreCase("not so good")) {
                System.out.println("Hope things get better soon!");
            }
        }
        
        scanner.close();
    }
}

两种方式都能实现你的需求,do-while在这种“先执行再判断”的场景下更直观,推荐优先使用哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:04:31