Can someone please explain what is going on in this method?
class test{
public static void main(String args[])
{
int[] x = new int[4];
int[] xy = new int[4];
//System.out.println(xy[0]);
for(int j : x) {
xy[j] += 1;
}
System.out.println(xy[0]); }}
So I thought that the enhanced for loop would be doing this
/**for(int j=0; j < x.length(); j++)
xy[j=0] = 1
xy[j=1]=1
xy[j=2]=1
xy[j=3]=1*/
but from what I've been reading, the enhanced for loop is doing for(int element:array). Still, I don't understand what the for loop in my method is actually doing. I have tried System.out.println() statements to check what was being put into the array xy, but it is either addresses or 0.
Thanks for all the help and apologizes if this is confusing.
For Each loop that you have used in here does assign j a value that is already assigned to array x (which in your case is 0 ).
As according to your case of x and xy array:-
x[0]=0; xy[0]=0
x[1]=0; xy[0]=0
x[2]=0; xy[0]=0
x[3]=0; xy[0]=0
Describing for each loop according to your program case:-
for(j : x)
This implies it will run for 4 times which is the length of your array x.
when running first time the following process will happen
j=x[0] (so j=0 coz x[0] according to your case)
xy[0]=xy[0]+1 (so now xy[0] value becomes 1)
Similarly
for the second run of for each
j=x[1] (so j=0 coz x[0] according to your case)
xy[0]=xy[0]+1 (so now xy[0] value becomes 2 as in previous for each run xy[0]=1)
So all in all finally you will have xy[0]=4 at the end of 4th run of for each loop.
Finally the print statement will print 4.
int[] x = new int[4];
This creates an array of 4 elements. Each element's value is 0.
for(int j : x) {
xy[j] += 1;
}
This iterates through all the values of x. At each iteration, j is the next element in x, but since all elements are initialized to 0, j is always 0. So, the 4 iterations increment xy[0].
Here in the advanced for loop, the int j does not represent the index. Rather it represents the values in the xy[] array. It is not possible to get the index of advanced for loop. If you want index, then you might have to use ordinary for loop.
Ex. If you have
xy[]={5,8,3,4};
for(int j:xy)
{
println(j);
}
then the output would be
5
8
3
4
It should be straight-forward to find out, if you trace through using debugger.
In brief, it is getting each value in x, and use the value as index to increment corresponding value in xy.
It will be more obvious if you initialize both array with meaningful values:
int[] x = {1,1,3,3}
int[] xy = new int[4]; // initialized to 0 by default
after your piece of code, you will find xy containing {0,2,0,2}.
You should understand how enhanced-for-loop is expanded for array:
for (T v : arr) {
// do something
}
is transformed to
for (int i = 0; i < arr.length; ++i) {
T v = arr[i];
// do something
}
Obviously your understanding on how enhanced for loop being expanded is wrong.
In your case you need only for-loop and not enhanced for-loop:
for(int j = 0 ; x.length > j; j ++) {
xy[j] += 1;
}
Problem with your code is that your loop traverse only at index 0 of xy hence you get xy as [4, 0, 0, 0]
int[] x = new int[4];//default values [0, 0, 0, 0]
int[] xy = new int[4]; //default values [0, 0, 0, 0]
for(int j : x) { // j is always 0
xy[j] += 1;// xy[0] += 1
}
You can use the for-loop instead:
for(int i = 0 ; x.length > i; i ++) {
xy[i] += 1;
}
If you want to still use for each then here is the example
a[]={1,2,3,4};
for(int i:a)
{
println(i);
}
Hope it helps!
Related
So I was trying to produce an arraylist where the even indexes were all filled. Something like this [1, -, 1, -, 1, -........]. But it's giving me an index out of bounds error. Why is that?
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<>(10);
for (int i=0; i<11; i+=2) {
a.add(i, new Integer(1234));
}
}
}
Remember indices always start with 0.
You've created an arraylist with size 10, which means you should iterate through index 9, not 10.
Your for loop should be:
for (int i = 0; i < 10; i += 2)
Arrays use zero based indexing meaning you can reference a[0] through a[9]. so your constraint in the for loop
Should be i < 10. I’ll edit this answer and give more detail when I get home.
First, you loop constraint is off, for an array (and ArrayList) of size 10, indices are 0 through 9, means you need to check for i < 10.
Second, the parameter of ArrayList constructor (10 in this case) is the capacity, but not size - it's still empty, no actual elements in there. So you need to add zeroes (or nulls) in the loop too:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
a.add(1234);
} else {
a.add(0); // or a.add(null)
}
}
i am trying to formulate a for loop that will take an array, for instance of 5 elements, and will allow me to treat a[0] as if it is after a[4], and a[4] as if it was before a[0].
I cannot change the array, and it stores a thread in each element, so i would rather make it as simple as possible to not corrupt the contents of the thread(threads are synchornized and using reentrantlock - so the question is only about array).
I want to make this simple for loop:
for (int i = 0; i < ARRAYSIZE; i++)
to allow me to treat it as if it was a cyclic array. I thought of using the mudolo operation to achieve that, but that doesn't work either. here's what i tried:
for (int i = i+1 % n; i < ARRAYSIZE; i++)
but that doesn't work as well. What I am trying to do is basically check if array[i] is larger than array[i+1] or array[i-1].
would appreciate your assistance.
Use the modulo operator on the loop variable i by the size of the array:
public static void main(String [] args) {
int [] arr = {1, 5, 4, 3, 3, 4, 3, 1};
int ARRAYSIZE = arr.length;
for (int i = 0; i < ARRAYSIZE; i++) {
int index = i % ARRAYSIZE;
int indexUpper = (i + 1) % ARRAYSIZE;
//access array using index
if (arr[index] == arr[indexUpper]) {
System.out.format("Elements %d and %d are equals.\n", index, indexUpper);
}
}
}
Note how for the upper value you want to cycle through, you need to do (i + 1) % ARRAYSIZE to ensure you get the next element. To get the element two places over, add 2 instead, or whatever modifier you choose.
This test shows how elements 7 and 0 are equal because it is cyclical.
Output:
Elements 3 and 4 are equals.
Elements 7 and 0 are equals.
I am working on an assignment where I need to create two arrays, then look through them and create a new array that holds any values inside of both the first two. Originally, I was close to accomplishing this by making an arraylist but my lab professor told me that wasn't allowed so I needed to re-start and didn't have enough time to figure out the solution.
If you'd like to see the whole code I have now: http://pastebin.com/thsYnj2z
I am really struggling with this loop here:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
k++;
System.out.println(ArrA[k]);
break;
}
My output is remaining 0 for my ArrA[k] array. I can't seem to trouble shoot this issue on my own.
try making these changes
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]); // or print them all later
k++;
break; // break to outer loop
}
}
}
note
Assuming OP has correctly initialized ArrA
note2
Assuming that only unique values are required, hence the breaking
Does your solution require that no values are duplicated in ArrA? Or are duplicate values allowed? For example, if some values occur multiple times in each array, you could get multiple matches on the same number.
If duplicates aren't a problem:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++){
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++;
}
}}
As I understand it, the problem is to take 2 arrays, and produce a third array which is a Union of the first 2. Union of 2 sets being the subset of the values found in both sets.
Your code was missing some braces, so put those back in there. Also you wont want to print the k+1th item after you just put a value in ArrA[k] im assuming.
Otherwise you were pretty much there. The break terminates the inner loop and allows the outer loop to increment i and continue on. This is because you have already found a match, no need to continue searching, just move onto the next index in Xarr.
Algorithm goes like this: For each value in X, search Y for a match. If it is found, add this value to A.
for(int i = 0 ; i < Xarr.length ; i++) {
for(int j = 0 ; j < Yarr.length ; j++) {
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++; //you probably want to increment k after you add to ArrA, not before
break;
}
}
}
public static void main(String... args){
int[] xArr = {1, 1,1,1,1,1};
int[] yArr = {1, };
int[] kArr = new int[xArr.length > yArr.length ? xArr.length : yArr.length];
int k = 0;
for(int x = 0; x < xArr.length; x++){
for(int y = 0; y < yArr.length; y ++){
int xNum = xArr[x];
int yNum = yArr[y];
if(xNum == yNum) kArr[k++] = xNum;
}
}
int[] resizedKArr = new int[k];
for(int i = 0; i < resizedKArr.length; i++) resizedKArr[i] = kArr[i];
Arrays.sort(resizedKArr);
for(int x : resizedKArr) System.out.println(x);
}
First, xArr and yArr are given some random numbers, and then kArr is initialized with the size of the lagest array we are comparing with to ensure the array has enough space to hold similar values.
Then, in the next section we do a loop inside of a loop to compare the values against each other and if they are similar then k++ and set the next value in the array. This goes on until the loops are completed, notice there really is never a need to break from either loop until all values are compared. At that point the loops break themselves and move on to the next bit of code.
The last section is just to create an array of the same size as k and move the values over, I don't know the requirements of your studies, although when using primitives like this you may want to do this in case you have a matching 0 as a number. Otherwise you'll have a ton of 0s filling the empty spaces of your array.
And lastly, we just sort the array for good measure and print it out.
Hope I've answered your question and you get something out of this post!
The problem is printing ArrA[k] after k++. Try increasing line after print.
An integer array stores values 3,2,3,4,5. I am trying to create a program that increments these values by 2 and then saves the result into the same array using a for loop. I tried but something is wrong with my code, here:
public class ArrayClass {
int a[] = {2, 3, 3, 4, 5};
}
public class ArrayObject {
public static void main(String[] Ella) {
int a[] = new int[5];
int i;
for (i = 2; i < a.length; i = i + 2) {
a[i] = i + 2;
System.out.println(a[i]);
}
}
}
This should work:
for (i = 0; i < a.length; i++) {
a[i] += 2;
System.out.println(a[i]);
}
You see, when increasing every single value of an array, the index has to be 0 and max the array's length. By adding one to i, the indexing of the array increases by one, which means the next number will be increased by two. what you did was add two to the "i" variable which means that only 3 of the varialbes would have been changed.
Please make below change to your code.It will work.
for (i = 0; i < a.length; i++) {
a[i] = a[i] + 2;
System.out.println(a[i]);
}
The error is that when you do i = i + 2, you are just incrementing the position index, not the actual value in that position.
you need to do:
a[i] = a[i]+2;
Let me explain what a[i] is:
|3|2|3|4|5|
1 2 3 4 5
The first row are the values. The second row is the index. "Index" means the position number of each of positions in the array.
Another problem is that, when you initialise i, it need to be i=0. That is because i array indices (plural of index) always start from 0. That means that a[0] is the first position in the array That would be number 3 from your data set.
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--)