I have made 2-D array to store patterns[user defined] and it's features [user can decide No of features for each pattern].I have to divide this structure into two parts TR1 and TR2 such that half features for each pattern goes in TR1 and remaining half goes in TR2. Code for the same
int n;//No of Patterns
int f=0;;//No of Features
System.out.println("Enter No of Patterns:");
n=Integer.parseInt(input.readLine());
//2-D array to store Features
int pattern[][]= new int[n][20];
int tr1[][]=new int[n][20];//TR1
int tr2[][]=new int[n][20];//TR2
//No of Features for each Pattern
for(int i=0;i<n;i++)//NO of Features for each Pattern
{
System.out.println("Enter No of Features for Pattern "+(i+1)+" : ");
f=Integer.parseInt(input.readLine());
pattern[i]=new int[f];
tr1[i]=new int[f/2];//definining size of TR1
tr2[i]=new int[f/2];//definining size of TR2
}
//Features of each pattern
for(int i=0;i<n;i++)
{
System.out.println("Enter Features for Pattern "+(i+1)+" : ");
for(int j=0;j<pattern[i].length;j++)
{
pattern[i][j]=Integer.parseInt(input.readLine());
}
}
//Split into TR1 & TR2
for(int i=0;i<n;i++)
{
for(int j=0;j<pattern[i].length/2;j++)
{
tr1[i][j]=pattern[i][j];
}
int x=0;//Fill TR2 from 0 index
for(int j=pattern[i].length;j<pattern[i].length;j++)
{
tr2[i][x]=pattern[i][j];
x++;
}
}
//Print Features of each pattern
for(int i=0;i<n;i++)
{
for(int j=0;j<pattern[i].length;j++)
{
System.out.print(" "+pattern[i][j]+" ");
}
System.out.println();
}
//Print TR1
for(int i=0;i<n;i++)
{
for(int j=0;j<tr1[i].length;j++)
{
System.out.print(" "+tr1[i][j]+" ");
}
System.out.println();
}
//Print TR2
for(int i=0;i<n;i++)
{
for(int j=0;j<tr2[i].length;j++)
{
System.out.print(" "+tr2[i][j]+" ");
}
System.out.println();
}
The issue is all the values in TR2 become 0 in output.But TR1 output is correct.
In the for
loop the condition, j < pattern[i].length
is false because:
int j = pattern[i].length;
Since the condition is false for the first time the statements inside for
loop is not executing at all.That's why the elements of TR2
remains uninitialized that's why elements of TR2
becomes 0
. .
for(int j=pattern[i].length;j<pattern[i].length;j++)
{
tr2[i][x]=pattern[i][j]; //Never executes
x++; //Never Executes
}
Checkout the link it'll help. java-how-to-split-a-2d-array-into-two-2d-arrays
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.