本文介绍了为什么Arrays.sort(arr)返回0值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import java.util.*;
import java.util.Arrays;
class stoner {

    public static void main(String[] args)
    {
        Scanner ob = new Scanner(System.in);
        int t = ob.nextInt();
        int arr[] = new int[501];
        while(t-- > 0)
        {
            int s = ob.nextInt();
            for(int i = 0;i<s;i++)
            {
                arr[i] = ob.nextInt();
                Arrays.sort(arr);
            }
            for(int i = 0;i<s;i++)
                System.out.print(arr[i]+" ");
        }
    }
}

输入:1(测试用例)5(数组大小)5 2 3 1 4(数组元素)

INPUT:1(the test case)5(size of array)5 2 3 1 4 (the array elements)

输出:0 0 0 0 0

OUTPUT:0 0 0 0 0

为什么即使使用了这种排序功能,我们仍然得到0的答案?

Why even after using this sort function we are getting 0's as answer???

推荐答案

如果仅填充数组的5个元素(您输入5作为数组的大小"),则数组的大多数501个元素将包含0.默认情况下,对数组进行排序后,0会位于您输入的正值之前.

If you only fill 5 elements of the array (you entered 5 as the "size of array"), most of the 501 elements of your array will contain 0s by default, and after sorting the array, the 0s come before the positive values you entered.

此外,在将所有输入分配给数组之后,应该只对数组进行一次排序.

In addition, you should sort the array just one time, after assigning all the inputs into the array.

    Scanner ob = new Scanner(System.in);
    int t = ob.nextInt();
    while(t-- > 0)
    {
        int s = ob.nextInt();
        int[] arr = new int[s]; // give the array the correct length
        for(int i = 0; i<s; i++)
        {
            arr[i] = ob.nextInt();
        }
        Arrays.sort(arr); // sort after reading the inputs
        for(int i = 0;i<s;i++)
            System.out.print(arr[i]+" ");
    }

这篇关于为什么Arrays.sort(arr)返回0值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:49