Java循环中如何分别记录每次输入?仅最后一次输入输出问题求助
Hey there! Let's break down why your code is only printing the last number you entered, and how to fix it so you can record and output every input.
The Root Problem
You're using a single integer variable n to store each input value. Every time you run n = ns.nextInt();, it replaces the previous value of n with the new input. By the time your loop finishes, n only holds the 5th number you entered (5 in your test case)—that's why you see five copies of 5 instead of each unique input.
The Solution: Use an Array (or Collection) to Store Multiple Values
Since you know you need to collect exactly 5 inputs, an array is the simplest way to keep track of each one separately. Here's your modified code:
Scanner ns = new Scanner(System.in); // Create an array with 5 slots to hold each input int[] inputNumbers = new int[5]; int i = 0; while(i < 5) { System.out.println("enter a number"); // Store each input in the array's current index inputNumbers[i] = ns.nextInt(); i++; } // Print each stored number from the array for(int num : inputNumbers) { System.out.println(num); }
What Changed?
- We replaced the single
nvariable with anint[] inputNumbersarray. This gives us 5 distinct positions to save each input. - Inside the loop, we assign each new input to
inputNumbers[i]—so the first input goes toinputNumbers[0], the second toinputNumbers[1], and so on up to the 5th input ininputNumbers[4]. - After collecting all inputs, we use a for-each loop to iterate through the array and print every stored value. Now when you enter 1, 2, 3, 4, 5, you'll get each number printed in the order you entered them.
Bonus: If You Don't Know the Input Count Upfront
If you ever need to collect a variable number of inputs, you can use an ArrayList<Integer> instead of an array. Here's a quick example of that approach:
Scanner ns = new Scanner(System.in); ArrayList<Integer> inputList = new ArrayList<>(); int i = 1; while(i <= 5) { // You could also loop until a specific input (like -1) to stop System.out.println("enter a number"); inputList.add(ns.nextInt()); i++; } // Print all elements in the list for(int num : inputList) { System.out.println(num); }
内容的提问来源于stack exchange,提问作者Daniel Geneta

