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

Java温度转换器无法输入起始温度单位问题排查

问题原因

问题出在Scanner的输入处理逻辑上:当你用sc.nextInt()读取温度数值后,输入缓冲区里会残留一个换行符(就是输入数字后按下回车产生的)。后续调用sc.nextLine()时,它会直接读取这个空的换行符,导致unit变量变成空字符串,无法匹配任何if/else条件分支,程序因此跳过了单位判断和转换结果的输出。

解决方案

有两种常用的修复方式:

方法1:消耗残留的换行符

在sc.nextInt()之后,额外调用一次sc.nextLine()清空缓冲区里的换行符:

System.out.println("Enter a temperature: ");
int temperatureNumber = sc.nextInt();
sc.nextLine(); // 消耗输入数字后留下的换行符
int newCel = ((temperatureNumber-32) * 5/9);
int newFah = ((temperatureNumber * 9/5) + 32);

方法2:统一用nextLine()读取输入(更健壮)

直接用sc.nextLine()读取整个输入行,再转换为整数,彻底避免换行符残留问题,同时能更好地处理异常输入:

System.out.println("Enter a temperature: ");
// 先读取整行输入,再转换为整数
int temperatureNumber = Integer.parseInt(sc.nextLine());
int newCel = ((temperatureNumber-32) * 5/9);
int newFah = ((temperatureNumber * 9/5) + 32);
额外优化建议

当前代码用int类型存储温度和转换结果,会丢失小数精度(比如33°F转°C是0.555...,用int会截断为0)。建议改用double类型保留精度:

double temperatureNumber = Double.parseDouble(sc.nextLine());
double newCel = ((temperatureNumber-32) * 5/9);
double newFah = ((temperatureNumber * 9/5) + 32);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 23:55:27