簡體   English   中英

在Java中按升序對數組進行排序

[英]Sorting an array in ascending order in java

我正在嘗試解決一個Java問題,在這里我必須按升序對數字進行排序。 我的代碼有效,直到我在其中輸入一個負整數。

import java.util.Scanner;
import java.util.Arrays;
public class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int input = sc.nextInt();

        int[] numbers = new int[input];

        for (int i = 0; i < numbers.length; i++) {
            int a = sc.nextInt();
            numbers[a] += a;
        }
        for (int i = 1; i < numbers.length; i++) {
                System.out.println(i + " " + numbers[i] / i);
        }
    }
}

我想將第9行中的數字設置為輸入,但是當我輸入較大的值或負整數時會遇到錯誤。 有幫助嗎?

這基本上是我需要解決的問題:

輸入:

5
-3
100
-1
-2
-1

輸出:

-3 1
-2 1
-1 2
100 1

Arrays.sort()是一個內置函數,可幫助您對數組進行排序

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int input = sc.nextInt();
    int[] numbers = new int[input];

    for (int i=0; i <numbers.length; i++) {
        int a = sc.nextInt();
        numbers[i] = a;
    }
    sc.close();

    Arrays.sort(numbers);

    int temp=numbers[0];
    int count=1;
    for(int i=1; i<numbers.length; i++){
        if(numbers[i]==temp){
            count++;
        }else{
            System.out.println(temp + " " + count);
            count=1;
            temp=numbers[i];
        }
    }
    System.out.println(temp + " " + count);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM