Java程序运行时while循环跳过首次迭代是什么原因导致的?
问题根因
Scanner类的nextInt()方法仅读取输入流中的整数部分,不会消耗整数末尾的换行符(\n),该换行符会一直残留在输入缓冲区中。- 首次加/乘运算结束后,进入下一轮外层
while循环时,scan.nextLine()会直接读取缓冲区中残留的空换行,得到空字符串,不会触发用户输入等待逻辑,空字符串不匹配multiply/add分支,直接进入下一次循环,因此会连续打印两次操作提示。
修复方案
推荐在所有nextInt()调用后,额外调用一次nextLine()消耗残留的换行符,修正后的代码如下:
import java.util.Scanner; public class myfun { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int totalNumbers; int product = 0; int count = 0; int sum = 0; String choice = "choice"; System.out.print("You can add up to ten numbers.\n"); while(! choice.equalsIgnoreCase("stop")){ System.out.print("Would you like to add or multiply? (Enter stop to be done)"); choice = scan.nextLine(); if (choice.equalsIgnoreCase("multiply")) { product = 0; System.out.print("How many numbers would you like to multiply?"); totalNumbers = scan.nextInt(); scan.nextLine(); // 消费数字输入后残留的换行符 count = 0; System.out.print("Please enter " + totalNumbers +" numbers."); product +=scan.nextInt(); count++; while (count < totalNumbers) { product *= scan.nextInt(); count++; } scan.nextLine(); // 消费最后一个数字输入后残留的换行符 System.out.println("The product is " + product); } else if (choice.equalsIgnoreCase("add")) { sum = 0; System.out.print("How many numbers would you like to add?"); totalNumbers = scan.nextInt(); scan.nextLine(); // 消费数字输入后残留的换行符 count = 0; System.out.print("Please enter " + totalNumbers +" numbers."); sum +=scan.nextInt(); count++; while (count < totalNumbers) { sum += scan.nextInt(); count++; } scan.nextLine(); // 消费最后一个数字输入后残留的换行符 System.out.println("The sum is " + sum); } } System.out.print("Come again!"); scan.close(); } }
也可以选择统一用nextLine()读取所有输入,再手动转换为整数类型,从根源上避免不同读取方法的逻辑差异问题。
内容的提问来源于stack exchange,提问作者Jacob Buckingham
相关产品推荐
相关产品推荐

