数组以Java中的降序顺序排列

时间:2015-10-26 21:41:31

标签: java arrays reverse

如何用Java中的降序排序这些年份?
样本输入:

  

1 1996 2 2015 3 2000

预期产出:

  

ID:2(2015)
  ID:3(2000)
  ID:1(1998)

以下是我试过的代码:

import java.util.Collections;
import java.util.Scanner;

public class ArrayYear {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int[] arr = new int[3];
    int[] year = new int[3];

    // read element into array
    for (int i = 0; i < arr.length; i++)
    {
      // input value
      arr[i] = in.nextInt(); 
      year[i] = in.nextInt();
    }

    // reverse array 
    for (int j = i + 1; j < year.length ; ++j)
    {
      if ( year[i] < year[j])
      {
        int temp = year[i];
        year[i] = year[j];
        year[j] = temp;
      }
    }

    for (int i = 0; i < arr.length; i++)
    {
      // print array
      System.out.println("ID :" + arr[i] + "(" + year[i] + ")");
    }
  }
}

2 个答案:

答案 0 :(得分:1)

尝试应该适用于阵列反转

for (int i = arr.length; i = 0; i--)
  {
   // print array
   System.out.println("ID :" + arr[i] + "(" + year[i] + ")");
  }

答案 1 :(得分:0)

import java.util.Collections;
import java.util.Scanner;

public class ArrayYear {

    public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    int[] arr = new int[3];
    int[] year = new int[3];

    // read element into array
    for (int i = 0 ; i < arr.length; i++)
    {
     // input value
     arr[i] = in.nextInt(); 
     year[i] = in.nextInt();

      // reverse array year[i] in descending order
     for (int j = 0 ; j < year.length ; j++)
      {
        if ( year[i] < year[j] )
        {
        int temp = year[i];
        year[i] = year[j];
        year[j] = temp;
        }
      }                 
    }

      for (int i = arr.length-1 ; i >= 0 ; i--)
      {
      // print array
       System.out.println("ID :" + arr[i] + "(" + year[i] + ")");   
      }
   }
}
      //my output :      
      ID :3(2001)
      ID :2(2000)
      ID :1(1988)

      //sample output:
      ID: 2 (2001)
      ID: 3 (2000)
      ID: 1 (1998)