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();
}
}
The above code compiles fine however on running i am getting an error as follows:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Sorting.enterArray(2dsort.java:76)
at Sorting.main(2dsort.java:87)
please help !
You are initializing your arrays before setting the values of m
and n
, so you get empty arrays :
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];
You should create your arrays after initializing m
and n
:
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];
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.