2d排序java中的意外运行时错误

时间:2015-09-07 09:54:55

标签: java sorting

    import java.util.Scanner;
    class Sorting
    {
    static int m,n;
    static int x=0;`enter code here`
    static int b[]=new int[m*n];
    static int a[][]=new int[m][n];
    static void print()
    {
    for(int i=0;i<m;i++)
    {
    for(int j=0;j<n;j++)
    {
    System.out.print(+a[i][j]);
    }
    System.out.println();
    }
    }

    static void convertBack()
    {
    for(int i=0;i<m;i++)
    {
    for(int j=0;j<n;j++)
    {
    a[i][j]=b[x];
    x++;
    }
    }

    }

    static void sort()
    {
    for(int i=0;i<m*n;i++)
    {
    for(int j=0;j<m*n;j++)
    {
    if(b[i]>b[j])
    {
    int temp=b[i];
    b[i]=b[j];
    b[j]=temp;
    }
    else
    {
    continue;
    }
    }
    }
    }

    static void convert()
    {
    for(int i=0;i<m;i++)
    {
    for(int j=0;j<n;j++)
    {
    b[x]=a[i][j];
    x++;
    }
    }
    }

    static void enterArray()
    {
    Scanner in=new Scanner(System.in);
    System.out.println("Enter the elements");
    for(int i=0;i<m;i++)
    {
    for(int j=0;j<n;j++)
    {
    a[i][j]=Integer.parseInt(in.nextLine());
    }
    }
    }
    public static void main(String args[])
    {
    Scanner in=new Scanner(System.in);
    System.out.println("Enter the number of rows");
    m=Integer.parseInt(in.nextLine());
    System.out.println("Enter the number of columns");
    n=Integer.parseInt(in.nextLine());
    enterArray();
    convert();
    sort();
   convertBack();
   print();
    }
    }

以上代码编译正常,但在运行时我收到如下错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at Sorting.enterArray(2dsort.java:76)
        at Sorting.main(2dsort.java:87)

请帮忙!

1 个答案:

答案 0 :(得分:0)

在设置mn的值之前,您正在初始化数组,因此您将获得空数组:

static int m,n; // both are 0 by default
static int b[]=new int[m*n]; // equivalent to new int [0];
static int a[][]=new int[m][n]; // equivalent to new int [0][0];

初始化mn后,您应该创建数组:

m=Integer.parseInt(in.nextLine());
System.out.println("Enter the number of columns");
n=Integer.parseInt(in.nextLine());
b=new int[m*n]; 
a=new int[m][n];
...