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

Java数组输出意外按升序排列,求原因及输入顺序输出方案

Why Your Output Is Sorted & How to Fix It

Hey there! Let's break down why your output is coming out in numerical order, and get it to match your input sequence instead.

The Root Cause

The issue lies in your final output loop:

for (i = 1; i < count.length; i++) {
    if (count [i] > 0) {
        System.out.printf("Number %d occurs %d times\n", i, count [i]);
    }
}

This loop iterates from 1 to the end of the count array, using the array index as the number you're checking. Since array indices increment from smallest to largest, your output automatically gets sorted by number values—not the order you entered them.

Solution 1: Use a LinkedHashMap (Cleanest Approach)

LinkedHashMap preserves the order in which elements are added, making it ideal for your use case. It lets you count occurrences and keep track of input order in one structure.

Here's the modified code:

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Quenten's Copy");
        Scanner input = new Scanner(System.in);
        Map<Integer, Integer> numberCount = new LinkedHashMap<>();

        System.out.print("Enter seven numbers: ");
        for (int i = 0; i < 7; i++) {
            int num = input.nextInt();
            // Update count: add 1 if the number exists, set to 1 if it's new
            numberCount.put(num, numberCount.getOrDefault(num, 0) + 1);
        }

        // Print in the exact order numbers were entered
        for (Map.Entry<Integer, Integer> entry : numberCount.entrySet()) {
            System.out.printf("Number %d occurs %d times\n", entry.getKey(), entry.getValue());
        }
        input.close();
    }
}

When you run this, your output will match the sequence you typed. The LinkedHashMap remembers the order of first occurrences, so the loop iterates through entries in that original input order.

Solution 2: No Collections (For Beginners)

If you haven't learned about collections yet, you can use two arrays: one to store all inputs, and another to track unique numbers in the order they first appeared.

Here's how that works:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Quenten's Copy");
        Scanner input = new Scanner(System.in);
        int[] allNumbers = new int[7]; // Store all 7 user inputs
        int[] count = new int[1000000]; // Track how often each number appears
        int[] uniqueNumbers = new int[7]; // Track first occurrence order
        int uniqueIndex = 0;

        System.out.print("Enter seven numbers: ");
        for (int i = 0; i < 7; i++) {
            allNumbers[i] = input.nextInt();
            int num = allNumbers[i];
            
            // Add to uniqueNumbers only if we're seeing this number for the first time
            if (count[num] == 0) {
                uniqueNumbers[uniqueIndex++] = num;
            }
            count[num]++;
        }

        // Print using the uniqueNumbers order (matches input sequence)
        for (int i = 0; i < uniqueIndex; i++) {
            int num = uniqueNumbers[i];
            System.out.printf("Number %d occurs %d times\n", num, count[num]);
        }
        input.close();
    }
}

This works because uniqueNumbers only adds a number the first time it's entered, so its order mirrors your input. The final loop iterates through this array instead of the entire count array, ensuring output matches input order.

内容的提问来源于stack exchange,提问作者Quenten Guiles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:07:33