[英]Dividing array into two different arrays
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. 我已经制作了一个二维数组来存储模式[用户定义],它的特征是[用户可以决定每个模式的特征数]。我必须将此结构分为两部分TR1和TR2,以便每个模式的一半特征都进入TR1和其余的一半进入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. 问题是TR2中的所有值在输出中都变为0,但是TR1输出正确。
In the for
loop the condition, j < pattern[i].length
is false because: 在
for
循环中,条件j < pattern[i].length
为false,因为:
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
循环内的语句根本不执行,这就是TR2
的元素保持未初始化的原因,这就是TR2
的元素变为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
java如何将一个2d数组拆分为两个2d数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.