Java程序部分代码循环4次才执行后续语句的问题排查
问题分析:为什么你的代码会重复请求输入多次才继续?
我一眼就瞅出问题所在啦——你在每个获取输入的方法里都新建了一个Scanner实例来读取System.in,这可是个典型的输入流使用错误!
问题根源
System.in是全局共享的输入流,所有基于它创建的Scanner都会共用同一个输入缓冲区:
- 当你在
getWidth()里用keyboard.nextDouble()读取完宽度后,输入时按下的回车键(换行符\n)会留在缓冲区里。 - 后续调用
getLength()时,新创建的Scanner会先读取到这个残留的换行符,nextDouble()会跳过空白字符,但这种多实例操作输入流的行为很容易导致缓冲区状态混乱,进而出现反复触发输入请求的情况,也就是你说的“循环4次后才继续”。 - 另外你原来的
getArea()和displayData()方法根本没有接收宽度、长度的参数,完全无法完成计算和显示的功能,这也是个隐性问题。
修正方案
只需要创建一个Scanner实例,让所有方法复用它,同时调整方法的参数传递逻辑,确保数据能在方法间正常流转:
import java.util.Scanner; public class Main { // 定义全局复用的Scanner实例 private static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { double width = getWidth(); double length = getLength(); double area = getArea(width, length); displayData(width, length, area); // 程序结束前关闭Scanner释放资源 keyboard.close(); } public static double getWidth() { System.out.print("Enter the width of the rectangle: "); return keyboard.nextDouble(); } public static double getLength() { System.out.print("Enter the length of the rectangle: "); return keyboard.nextDouble(); } public static double getArea(double width, double length) { return width * length; } public static void displayData(double width, double length, double area) { System.out.printf("Rectangle details:\nWidth: %.2f\nLength: %.2f\nArea: %.2f\n", width, length, area); } }
这样修改后,不仅解决了输入重复触发的问题,还让整个程序的逻辑更清晰,数据流转更合理。
内容的提问来源于stack exchange,提问作者anonymousdude123
相关产品推荐
相关产品推荐

