[英]Find the maximum of the length of 2 arrays
I am passing 2 arrays to the controller with different lengths, I want to execute a for loop and length of that will be the max of the length of 2 arrays. 我正在将2个数组传递给具有不同长度的控制器,我想执行一个for循环,其长度将是2个数组长度的最大值。 I am not getting how to execute that. 我不知道如何执行该操作。 I tried Math.max but its giving me error as cannot assign a value to the final variable length. 我尝试了Math.max,但由于无法将值赋给最终变量长度而给了我错误。
String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)
The no of elements in x and y are not fixed. x和y中的元素编号不固定。 it changes what we are passing from the front end. 它改变了我们从前端传递的内容。
Initialize the new array with the desired length: 用所需的长度初始化新数组:
String[] x = new String[Math.max(y.length,z.length)];
In case you don't need to create an array, just use the result of Math.max
as conditional to stop your loop: 如果不需要创建数组,只需使用Math.max
的结果作为条件来停止循环:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max()
operation into the array's initialization. 只需将Math.max()
操作带入数组的初始化即可。
String[] x = new String[Math.max(y.length, z.length)];
Here's an expansion for clarity: 为了清楚起见,这是一个扩展:
int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];
Edit: Unless, OP, you're not interested in creating another array... 编辑:除非,OP,否则您对创建另一个数组不感兴趣...
I want to execute a for loop and length of that will be the max of the length of 2 arrays 我想执行一个for循环,其长度将是2个数组的最大长度
Just bring your Math.max()
operation into your for
loop: 只需将您的Math.max()
操作引入for
循环中即可:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
int max_length = Math.max(y.length,z.length);
for(int i=0; i < max_length ; i++){
//...
}
you can use that max_length
to create a new String[]
if you are trying to create an array with total length of y and z arrays
, like 如果您尝试创建一个总长度为y and z arrays
,可以使用max_length
创建一个新的String[]
,例如
String[] newArray = new String[max_length];
Set a variable to the maximum length of the arrays, create a new array with that length and then loop until that point. 将一个变量设置为数组的最大长度,使用该长度创建一个新数组,然后循环直到该点。
int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
// Loop code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.