2015-09-07 75 views
-1
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

歡迎堆棧溢出。請在將來更加努力地設置代碼的格式 - 很難閱讀而且沒有縮進。請閱讀http://tinyurl.com/stack-hints –

回答

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]; 
... 
+0

我很抱歉,要求這樣愚蠢的問題該死!我完全錯過了:(謝謝你,太多了! –