You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java循环中如何分别记录每次输入?仅最后一次输入输出问题求助

Fixing Your Java Input Recording Issue

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 n variable with an int[] inputNumbers array. 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 to inputNumbers[0], the second to inputNumbers[1], and so on up to the 5th input in inputNumbers[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:41:50