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.
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.
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. 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:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max() operation into the array's initialization.
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...
I want to execute a for loop and length of that will be the max of the length of 2 arrays
Just bring your Math.max() operation into your for loop:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
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
}
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
String[] newArray = new String[max_length];
Related
So in java, This is what I'm trying to execute:
num [0]=list.get(2);
num [1]=list.get(4);
num [2]=list.get(6);
num [3]=list.get(8);
I have an arraylist of integers called list and I want to put the values that are in the even number indices starting at 2 into an array of integers called num in the indices 0,1,2,3,etc. My problem is, I'm trying to do this within a for loop but I'm not sure how to go about it. Here is what I have:
for (int i=0; i<list.size()-2; i++){
num[i] = list.get(i+2);
}
My problem here is, after incrementing i, my arraylist goes to the next index also instead of every other index. I've tried multiple variations of this loop but I keep coming to the same problem.
This should do it:
int max = list.size()/2;
if(list.size()%2==0) max-=1; // prevents IndexOutOfBounds for even list lengths
for (int i=0; i<max; i++){
num[i] = list.get(i*2 + 2);
}
You can try something like this.
for (int i=0,j=0; i<list.size()-2; i+=2,j++){
num[j] = list.get(i+2);
}
The loop should continue as long as the i is less then (list.size()-1)/2
List<Integer> list = Arrays.asList(0,1,2,3,4,5,6);
int size = (list.size()-1)/2;
int[] num = new int[size];
for (int i=0; i<size; i++){
num[i] = list.get(i*2+2);
}
System.out.println("num="+ Arrays.toString(num));
Here is DEMO
This should work:
for(int i = 0; i < list.size() - 2; i++)
num[i] = list.get((i * 2) + 2);
I already have one Array with random numbers between 0-999.
I also have created two new arrays, one with correct the size to hold all numbers 0-499, and one with the correct size for numbers 500-999.
Problem is to then loop through the Array holding all numbers and copying the right numbers 0-499 and 500-999 to the new Arrays.
Anyone know the correct way to do this? Have spent many days now trying to figure this out.
What i got so far:
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
Random generator = new Random();
System.out.print("How many numbers between 0 - 999?" );
int number= scannerObject.nextInt();
int [] total= new int[number];
for(int index = 0; index < total.length; index++ )
{
total[index] = generator.nextInt(1000);
}
System.out.println("Here are the random numbers:");
for(int index = 0; index < total.length; index++ )
{
System.out.print(total[index]+ " ");
}
int lowNumber=0;
int largeNumber = 0;
for(int index = 0; index < total.length; index++ )
{
if (total[index] < 500)
{
lowNumber++;
}
if (total[index] >= 500)
{
largeNumber++;
}
}
System.out.println();
System.out.println(lowNumber);
System.out.println(largeNumber);
int [] totalLownumber = new int [lowNumber];
int [] totalLargeNumber = new int [largeNumber];
for(int index = 0; index < total.length; index++ )
{ // TODO
}
}
2 of the approaches you can take are as follows:
You can go through the initial array, count the elements you have, and use the counter values to define the size of the arrays you need. You then go over the original array once again and copy the elements to their respective array. You can use the counter values once again (you would need to reset them first) to allow you to keep track in which array location will the current number need to go. This should be similar to what you are doing.
Consider using a variable length data structure such as a List (ArrayList in Java). This would allow you to go over your original array and assign the numbers to their respective list (let's call them largeNumberList and lowNumberList). Since these collections have a dynamic size, you would only need to traverse the array once and assign as you go along.
The latter approach is usually what is used more often, however, since it would seem that this question is related to homework, I would recommend you try both approaches and compare them.
Try this:
int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
if (total[index] < 500) {
totalLowNumber[lowIndex++] = total[index];
} else {
totalLargeNumber[largeIndex++] = total[index];
}
So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.
String[] month = {"Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
int[] monthArray = new int[12];
String[][] itemArray = new String[12][10];
Variables
monthArray[i] = input.nextInt();
itemArray[monthArray[i]-1][e] = input.next();
Store a maximum of 5 String values on user input's month.
for(int i=0;i<e;e++){
System.out.println(itemArray[monthArray[i]-1][i]);
}
Having a problem displaying the String values (it just keep repeating the first String value) under user input's month.
You are increasing e instead of i in the last loop. e is the limit and not the variable you use for the iteration and thus the loop will not terminate until you overflow int.
for(int i = 0; i < e; i++ /* Note the usage of i here*/) {
use i++ instead of e++
here e stands for the limit
and i stands for the variable.
Since you have a 2D array, maybe you want something more like this, to print out the values, once, the array has been populated.
String[][] itemArray = new String[12][10];
for(int i = 0; i < itemAreray.length; i++){
for (int j = 0; j < itemArray[i].legnth; j++){
System.out.println(itemArray[i][j]);
}
}
Unless you're having difficulty populating the array. Then that's a different problem
I have the code below:
int lines = 0;
while(lines < 2)
{
int[] oldarr = parr;
for(int i = 0; i < arrsize; i++)
System.out.print(" " + oldarr[i]);
System.out.println();
for(int i = 0; i < arrsize; i++)
{
if(i == 0)
parr[i] = 0;
else
parr[i] = Math.abs(oldarr[i] - oldarr[i-1]);
}
lines++;
}
parr is an array of integers of size [arrsize]. Each time through this loop I want to print the value of each index in parr, then set each index to the difference between the index before it and itself. Currently it gives me the correct (hardcoded) originally parr. But the next(first) iteration of changing parr gives me unexpected values; they are not even close to the difference between the two neighboring values..
Any ideas?
You aren't copying your array with this line:
int[] oldarr = parr;
The two variables are still pointing at the same array.
To get a copy, you can do:
int[] oldarr = Arrays.copyOf(parr, parr.length);
In your second for loop, you are setting the new value to the difference of the current value and the previous value, but the previous value was already changed in the previous iteration of the for loop.
Change your second for loop iteration to iterate through the array backwards, so your calculations don't depend on previous calculations.
for(int i = arrsize - 1; i >= 0; i--)