【问题标题】:How to print out the last item in an array如何打印出数组中的最后一项
【发布时间】:2014-03-03 14:42:24
【问题描述】:

我正在尝试创建一个程序,它将遍历输入的整数列表,将它们从最小到最大排序,然后打印出最后一项(最大)、输入的中间项和第一项(最小整数)。

从代码中可以看出,我有项目的平均值。

“bubbleSort”方法将它们按顺序排列并打印出排序后的数组。

有什么建议吗?

代码:

class statistics{
    public static void main(String agrs[]){
        System.out.println("Enter the number of integers you want to input?");
        int n = EasyIn.getInt();

        //declare arrey called numbers and give it the length of the number enter.
        int[] numbers = new int[n];

        for(int i=0; i<numbers.length; i++){
            System.out.println("Enter number: " + (i+1));
            numbers[i] = EasyIn.getInt();
        }// end of for loop
        // add a switch case for the print outs and a menu.
        bubbleSort(numbers);
        System.out.println("The average is " + averageMethod(numbers));
    }// end of main method.
    public static int averageMethod(int[] nums){
        int total=0;
        int average=0;
        for(int i=0; i<nums.length; i++){
            total = total+nums[i];
            average = total/nums.length;
        }// end of for loop
        return average;
    }// end of totalMethod

    public static void bubbleSort(int[] ar) {
        int temp;
        // this code does the bubble sort
        System.out.println();
        for(int i = ar.length -1; i>0; i--){
            for(int j=0;j<i; j++){
                if(ar[j]>ar[j+1]){
                    temp=ar[j];
                    ar[j]=ar[j + 1];
                    ar[j+1]= temp;
                }
            }
            System.out.print("The sorted array is : ");
            for(int b=0; b<ar.length; b++){
                System.out.print(ar[n] + ", ");
            }
            System.out.println();
        }
    } // end of buble sort
}// end of class.

【问题讨论】:

  • 所以你的排序工作,但问题是你想打印数组中间的大数、最小数和数字?
  • 是的,排序有效,但我想打印数组中间的最大、最小和数字。
  • 数组中间到底是什么意思。因为一个偶数大小的数组没有像中间这样的东西

标签: java arrays


【解决方案1】:

如果您有一个长度为n 的升序排序数组arr,则最小元素位于arr[0],最大元素位于arr[n - 1]

【讨论】:

    【解决方案2】:

    除了Smutje所说的,要拿到中间项: 如果 n 是奇数,那么它将是 arr[(n/2)+1],但如果 n 是偶数,则取决于您认为“中间”是什么,例如: 如果 n=4 那么 n/2 = 2 是第三个索引,(n-1)/2=1 是第二个索引,现在哪个是中间的?

    【讨论】:

      【解决方案3】:

      要打印第一个、中间和最后一个,您可以执行以下操作:

      if(numbers != null && numbers.length > 0) {
          System.out.println(numbers[0]);
          System.out.println(numbers[numbers.length / 2]);
          System.out.println(numbers[numbers.length - 1]);
      }
      

      另一个建议是不要使用冒泡排序:)

      【讨论】:

        猜你喜欢
        • 2017-09-08
        • 2021-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-29
        相关资源
        最近更新 更多