nextInt()执行后程序跳过for循环的Java问题排查
问题解决:循环未执行的原因及修复
你这段代码里循环跳过不执行的核心问题是for循环的条件写反了,导致循环入口条件不成立,直接跳过了循环逻辑。
问题分析
你写的循环条件是:
for (int i = 1; i >= num; i++)
当用户输入的水果数量num大于1时,初始值i=1,1 >= num的判断结果为false,循环直接不执行。正确的逻辑应该是让i从1开始,一直循环到等于num,所以条件应该改为i <= num。
另外,你已经通过s.nextLine()处理了nextInt()读取整数后残留的换行符,这部分处理是正确的,不需要修改。
修复后的完整代码
import java.util.*; public class FruitBasket { public static void main(String[] args) { Scanner s = new Scanner(System.in); Stack<String> stack = new Stack<>(); String select; System.out.println("Catch and eat any of these fruits: (Apple, Orange, Mango, Guava)"); System.out.print("How many fruits would you like to catch? "); int num = s.nextInt(); s.nextLine(); // 修改循环条件为 i <= num for (int i = 1; i <= num; i++) { System.out.print("Choose a fruit to catch. Press A(apple), O(orange), M(mango), G(guava) "); System.out.print("\nFruit " + i + " of " + num + ": "); select = s.nextLine(); stack.push(select); } } }
内容的提问来源于stack exchange,提问作者Francis Putnam
相关产品推荐
相关产品推荐

