System.out.print在while循环内无法正常输出的问题求助
问题原因
循环内的System.out.print提示无法显示,是因为标准输出流的缓冲区没有被即时刷新。Scanner.nextDouble()会阻塞程序等待输入,而print方法的输出会留在缓冲区里,直到缓冲区满、遇到换行或手动刷新时才会显示到控制台,导致用户看不到提示就进入了输入等待状态。
解决方案
有两种简单的修复方式:
方式一:使用println替代print
println方法在输出内容后会自动添加换行符并刷新缓冲区,能确保提示立即显示:
package FindingDuplicates; import java.util.Scanner; public class FindingDuplicates { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter a number: "); double input = in.nextDouble(); while(in.hasNextDouble()) { double previous = input; System.out.println("Please enter a number: "); input = in.nextDouble(); if(previous == input) { System.out.println("Duplicate found"); } } } }
方式二:手动刷新输出流
如果需要保持不换行的输出格式,可以在print之后调用System.out.flush()强制刷新缓冲区:
package FindingDuplicates; import java.util.Scanner; public class FindingDuplicates { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Please enter a number: "); System.out.flush(); double input = in.nextDouble(); while(in.hasNextDouble()) { double previous = input; System.out.print("Please enter a number: "); System.out.flush(); input = in.nextDouble(); if(previous == input) { System.out.print("Duplicate found"); System.out.flush(); } } } }
额外提示:使用double类型直接判断相等可能存在精度误差,若处理整数或需要精确比较的场景,建议改用int或BigDecimal类型。
内容的提问来源于stack exchange,提问作者Kyle
相关产品推荐
相关产品推荐

