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

Java中如何通过多字符布尔表达式关闭do-while循环?

问题根因
  • while循环条件逻辑错误
    你使用了逻辑或||作为多条件的连接符,该逻辑下只要有任意一个判断成立,整个表达式结果就为真。比如用户输入有效字符c时,userLetter != 'C'的判断结果为真,整个循环条件就会返回真,循环会持续执行永远无法退出。
    符合预期的逻辑是:只有当输入同时不等于四个有效字符时,才继续循环,需要把所有||替换为逻辑与&&。

  • 无效输入分支存在语法冗余和错误
    你在最后一个else分支中写的判断语句末尾多了一个分号,导致后续的合法提示打印语句不受if分支控制,无论输入是否有效都会执行。同时这个if判断本身是冗余的,代码走到该else分支时,已经说明输入不属于四个有效字符,不需要额外做判断。

修复后可正常运行的代码
import java.util.Scanner;

public class CelsToFaren
{
    public static void main(String[] args)
    {
        // 初始化扫描器
        Scanner sc = new Scanner(System.in);
        // 变量声明
        int celsius;
        int answerC;
        int farenheit;
        int answerF;
        char userLetter;
        do
        {
            // 初始化菜单选项
            System.out.println("Which temperature would you like to convert from? ");
            System.out.println(" >(C)elsius ");
            System.out.println(" >(F)arenheit ");

            // 用户输入C、c、F、f选择转换方向
            userLetter = sc.next().charAt(0);

            // 用户输入C或c的情况
            if (userLetter ==  'C' || userLetter == 'c')
            {
                System.out.print("Please enter the temperature: ");
                celsius = sc.nextInt();
                answerC = celsius * 9 / 5 + 32;
                System.out.println("The answer is: " + answerC + " Farenheit ");
            }
            // 用户输入F或f的情况
            else if (userLetter == 'F' || userLetter == 'f')
            {
                System.out.print("Please enter the temperature: ");
                farenheit = sc.nextInt();
                answerF = (farenheit - 32) * 5 / 9;
                System.out.println("The answer is: " + answerF + " Celsius ");
            }
            // 输入无效的情况
            else
            {
                System.out.println("Please enter a valid option");
            }

        } while (userLetter != 'c' && userLetter != 'C' && userLetter != 'f' && userLetter != 'F');
        sc.close();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:39:01