This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 5 years ago.
I am simply trying to iterate through every variable in an array of arrays:
Here's the working code:
int[][] mArray;
mArray = new int[2][2];
mArray[0][0] = 1;
mArray[0][1] = 2;
mArray[1][0] = 3;
mArray[1][1] = 4;
for (int i = 0; i < mArray.length; i++)
{
for (int x = 0; x < mArray[i].length; x++)
{
System.out.println(mArray[i][x]);
}
}
This prints out:
1
2
3
4
So Everything's fine.
However if I replace
"for (int x = 0; x < mArray[i].length; x++)"
with
"for (int x = 0; x < mArray[x].length; x++)"
It get the following error: "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2".
Can anyone explain why this error happens to occur? Both mArray[i].length and mArray[x].length result in a value of "2", so why does the second option not work?
Thanks in advance :)
Explanation is simple.
for (int x = 0; x < mArray[x].length; x++) {
// body
}
Before iterations: x=0
Statements execution order:
- 1st iteration: 0 < mArray[0].length == true; execute body; increment x
(x==1)
- 2nd iteration: 1 < mArray[1].length == true; execute body;
increment x (x==2)
- 3rd iteration: 2 < mArray[2].length cause
ArrayIndexOutOfBoundsException, because x==2 and length of mArray is 2
UPD: totally, it's wrong logic to replace i with x in inner cycle, because i - it's row counter, and x - counter for columns.
Related
This question already has answers here:
Java method to swap primitives
(8 answers)
Closed 4 years ago.
I have a question regarding a 1d array and what I am attempting to do with this array is changing the index value of any value within the array for example
int[] num = new[2,4,6,9]
and what I want to do with this array I want position 0 to become position 1 and position 1 to become 0. So the array would look like [4,2,6,9] and that part is easy enough to do but I am struggling with the parts that come after which is I would like for the array to continue down this path so [4,6,2,9]->[4,6,9,2] and I am struggling with that. So far I am using two array to try this but I am having difficulties. Also I am attempting to do this with all spots and not just the first one.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
temp[j] = temp2[i];
if (j != 0) {
temp[j - 1] = temp2[j];
}
}
revert(); //I use this methods to restore any changes made so I can attempt with the next spot
}
Keep only 1 for loop and 1 temp variable to swap your tab.
for (int i = 0; i < N; i++) {
tmp = tab[i];
tab[i] = tab[i + 1];
tab[i + 1] = tmp;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
int i, tem = 3;
i = tem;
for (int x = 0; x <= i; x++) {
for (int j = 1; j< tem; j++) {
System.out.println("a");
}
}
The above code prints a 8 times. I'm not able to understand why.
for (int j = 1; j < tem; j++)
The above code runs for j=1 to j=2, that is 2 times and will print
a
a
Now the for loop
for (int x = 0; x <= i; x++)
will execute the above printing 4 times (x = 0 to 3). So overall your code will print 8 times.
a //x=0
a
a //x=1
a
a //x=2
a
a //x=3
a
consider iteration one x=0 and tem=3 so inner for loop iterates twice for conditions j=1 and j=2. Second iteration now x=1 and tem=3 in this case also inner loop iterates twice for j=1 and j=2 .This process continues for x=2 and x=3 as well ,so finally first for loop condition gets passed for 4 times i.e x=0,x=1,x=2 and x=3 and inner for loop condition passes twice for every first for loop condition getting passed so it prints 4*2 times which is eight times
It should not print 'a' for 8 times. The following program print 'a' for 4*3=12 times.
public class HelloWorld{
public static void main(String []args){
int i, tem = 3;
i = tem;
for (int x = 0; x <= i; x++) {
for (int j = 1; j <= tem; j++) {
System.out.println("a");
}
}
}
}
Try executing the above program and you will get correct number of 'a' (12 times) instead of 8 a's.
The first for iterates from 0 to 3, that's 4 times.
The second for iterates from 1 to 3, that's 3 times.
Since the first for is inside the second, the print will happen 3 times * 4, that's 12.
If you need it to be 8 prints, you should change <= for an < either in the first or the second for.
Sometime is useful to use the debugger, and in cases like this where you are looping every now and then
printin the indexs to see/proof the "logic"
your code is kind of a pitfall with the indexs in the for loops
but you can replace the printline and verify that
the outter loop is from 0 to 3: 4 times
the inner loop is from 1 to 2: 2 times
ergo 4x2 times printing the char a
Example:
public static void main(String[] args) {
int i, tem = 3;
i = tem;
for (int x = 0; x <= i; x++) {
for (int j = 1; j < tem; j++) {
System.out.println("x: " + x + ",j:" + j);
}
}
}
I am getting array index out of bounds exception at the last line of the prog,
output[1][1] generates such an exception there. But the same thing remained normal in the previous loop.
{
int ict=66,total_slots=12,h1=15,index_count=65;
String output[][] = new String[ict][total_slots+1];
for (int x = 0; x < (ict); x++)
output[x][0] = Integer.toString(x);
for (int y = 0; y < (total_slots + 1); y++)
output[0][y] = Integer.toString(y);
for (int x = 1; x <= (index_count); x++ )
for (int y = 1; y <= (total_slots); y++)
output[x][y] = "n";
for (int x=1; x <= h1; x++) {
output[x][1]="y";//exception occurs here
limit[x]++;
}
}
{
int ict=66,total_slots=12,h1=15,index_count=65;
..................................................
..................................................
for (int x=1; x <= h1; x++) {
output[x][1]="y";//exception occurs here
limit[x]++;
}
}
At the last for loop, you recieve ArryIndexOutOfBoundsException , while trying to access the element output[13][1] cause your array width is only 13 i.e max index will be 12 but not more than that
Use total_slots instead of h1
Remember when you declare an array like String output[][]=new String[5][5]; then output[4][4] is the last element you can access since array indexes start at 0
you have declared your array as:
String output[][] = new String[ict][total_slots+1];
in your for loop you have
for( int x=1; x<=(ict); x++ )
for( int y=1; y<=(total_slots); y++)
output[x][y]="n";
On the very last iteration of the outer loop and the very first iteration of the inner loop, you are trying to access output[ict][0] which is what throws the exception. Remember that since 0 is the first index, ict - 1 will be the last valid index for the first dimension.
Try this:
String output[][] = new String[ict][total_slots]; //this is cleaner
for( int x=0; x<ict; x++ )
for( int y=0; y<total_slots; y++)
output[x][y]="n";
This way the last iteration of the outer loop would only go up to ict - 1
edit:
It seems you have edited the question significantly. Please do not edit your question in the future in response to answers, because this will only confuse new readers.
As your code stands right now, the only error (compile time no less, irrelevant to exceptions) is the fact that limit[x]++; is invalid because limit has not been declared in this scope. otherwise the code is legal and runs fine.
I am getting array index out of bounds exception at the last line of the prog, output[1][1] generates such an exception there.
Recheck the console output. You must have mistaken the erroring line, since there is no way to generate such an exception. The problem most probably lies in the limit[], which we don't know how it's declared.
Btw, the last line is limit[x]++ ;)
I'm new to Java.
I can't seem to understand why these two codes produce different outputs.
Please explain this to me.
What is the difference of y<=x; and y<=5;. As you can see the x is 5 too, I don't understand why I get different outputs.
for (int x = 0; x < 5; x++) {
for (int y = 1; y <=x ; y++) {
System.out.print("x");
}
for (int g = 4; g >= x; g--) {
System.out.print("*");
}
System.out.println();
}
Output:
*****
x****
xx***
xxx**
xxxx*
Code:
for (int x = 0; x < 5; x++) {
for (int y = 1; y <= 5; y++) {
System.out.print("x");
}
for (int g = 4; g >= x; g--) {
System.out.print("*");
}
System.out.println();
}
Output:
xxxxx*****
xxxxx****
xxxxx***
xxxxx**
xxxxx*
Basically the main difference is this line:
for(int y=1; y<=x; y++)
resp.
for(int y=1; y<=5; y++)
The number of times the loop is executed is different. Namely in the first case it is variable (so the number of 'x' increases), in the second case it is fixed (5 'x' printed each time).
(edit: typo)
xstarts at 0 so the first iteration has the condition y<=0, the second will have y<=1 and so on .. till y<=5
While the second one will have y<=5in every iteration, thats why you get xxxxx in every line.
In the first code you print x times the "x" String in each row.
for(int y=1; y<=x; y++) {
System.out.print("x");
}
BTW, it prints the following (which is different than what you claim in the question):
*****
x****
xx***
xxx**
xxxx*
In the second code you print 5 times the "x" String in each row.
for(int y=1; y<=5; y++) {
System.out.print("x");
}
As you can see the x is = 5 too
No, x iterates from 0 to 4, so in each iteration of the outer for loop, it has a different value.
In your first code your for(int y=1; y<=x; y++) for iterations of outer for loop is -
for(int y=1;y<=0;++y) (for first iteration of outer loop)
for(int y=1;y<=1;++y) (for second iteration of outer loop)
for(int y=1;y<=2;++y) (for third iteration of outer loop)
for(int y=1;y<=3;++y) (for fourth iteration of outer loop)
for(int y=1;y<=4;++y) (for fifth iteration of outer loop)
But in your second code its always -
for(int y=1; y<=5; ++y)
for all iterations of outer for loop.
It is very simple the will run for 5 time times and every itreation its value will be increamented by 1 i.e. from 0 to 4.
So in first loop inner loop will have the condition like this:
for (int y = 1; y <= x; y++) {
System.out.print("x");
}
But since in first loop the value of x is 0 hence it literally means:
for (int y = 1; y <= 0; y++) {
System.out.print("x");
}
But in the last iteartion of outer loop the value of x is 4 hence this is equivalent to:
for (int y = 1; y <= 4; y++) {
System.out.print("x");
}
So it iterates 4 times.
In your first example y is first less than x = 1 and during the next iteration it will be less x= 2 ... Because x values changes with your first for loop.
For the second example however you state that y have to be less than 5 which doesn't change at all.
They are different because in the first case your x varies from 0 to 4 based on :
for(int x=0; x<5; x++)
In the case second case x is fixed at 5.
I have replaced your two inner for loops with a new stringRepeat function. It might be easier to understand this way.
public class ForLoopStarsAndCrosses {
public static void main(String[] args) {
/// the total length ot the x's and stars
final int length = 5;
// start with 1 x until one less than the length (in this case 4)
for(int x = 1; x < length; x++) {
// the number of stars equals the total length minus the number of x's
final int nbStars = length - x;
// add the x's and the stars
final String output = stringRepeat("x", x) + stringRepeat("*", nbStars);
System.out.println(output);
}
System.out.println();
}
/** Repeat the string s n times */
private static String stringRepeat(String s, int n) {
String result = "";
for (int i = 0; i < n; i += 1) {
result += s;
}
return result;
}
}
Firstly, you should understand the difference between value and variable. Value is a constant as you write 5 but variable can be changeable.
For your question, first code and first round:
x = 1, y<= 1 and output: x
for(int y=1; y<=x; y++){
System.out.print("x");
}
but for the second code and first round:
y<=5 so output is: xxxxx
for(int y=1; y<=5; y++){
System.out.print("x");
}
it is very simple.
The purpose of loops (can be for, while, do-while) is that, how many number of times the same set of statements to be executed under a specific condition. "for" is a definite loop where there will be an index starting with an integer, keep increment it until the condition is achieved. "while" is a indefinite loop where there is no index and it will be executed until the condition is achieved. "do-while" is a loop similar to "while", which will be executed atleast once and then validates the condition for the next iteration.
Based on the above details,
for(int x=0; x<5; x++){
for(int y=1; y<=x; y++){
for(int x=0; x<5; x++){
for(int y=1; y<=5; y++){
The diff between these two conditions is that,
First condition:
In the first iteration, value of x is 0 and for the second loop y is started with 1.
Here when it compares the value with x which is 0 and 1<=0 which is false, this condition is failed and the statements under Y will not be executed and the control will go back control of x.
Second condition:
In the first iteration, value of x is 0 and for the second loop y is started with 1.
Here when it compares the value with 5, 1<=5 which is true, this condition is valid and the statements under Y will be executed and the control will go back control of x until y becomes 6 and condition checked is 6<=5 which is false, this condition is failed and the statements under Y will not be executed and the control will go back control of x
Note: Due to low reputation, I can't add comments and had to contribute this as an answer. Don't downvote this, instead suggest corrections by comment on the same.
When I run this class I am not getting a the sum/average. I am getting an error listed below. I am not sure why I am getting it. I am a student very new at this.
public class DebugEight2
{
public static void main(String[] args)
{
int[] someNums = {4,17,22,8,35};
int tot;
int x;
int sum = 0;
for(x = 0; x <= someNums.length; ++x)
tot = someNums[x];
sum = sum + someNums[x];
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum * 1.0 / someNums.length);
}
}
Error:
"Exception in thread "main" java.lang.ArrayIndexOutofBoundsException: 4 at DebugEight1.main (DebugEight1.java:17)"
Array index starts from 0 and goes till it's length -1 See that <= in your for loop. So this for(x = 0; x <= someNums.length; ++x) should be for(x = 0; x < someNums.length; ++x)
Problem is your loop condition, remove the equal sign like this
for(x = 0; x < someNums.length; ++x)
You should also wrapp the code which is supposed to be inside the loop into brackets (without them, only the next line after the for loop condition will be executed)
for(x = 0; x < someNums.length; ++x) {
tot = someNums[x];
sum = sum + someNums[x];
}
first you should remove = from <= someNums.length; i will look like this < someNums.length; and then change ++x to x++ if you put ++x when loop starts it will check condition < someNums.length; and then pluse one +1 to x and so on, currently your array length is 5 when loop goes on last increment its size is 6 and there is no item on 6 location thats why it is throwing exception so you have you change it ++x to x++
public class DebugEight2
{
public static void main(String[] args)
{
int[] someNums = {4,17,22,8,35};
int tot;
int x;
int sum = 0;
for(x = 0; x <someNums.length; x++) /// just change here
tot = someNums[x];
sum = sum + someNums[x];
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum * 1.0 / someNums.length);
}
}
Arrays are zero based and their indices go from 0 to someNums.length -1
You not only exceeding the bounds of the array but the variable sum is being assigned outside of scope of the loop. Adjust the upper bounds of the array and add braces:
for (x = 0; x < someNums.length; x++) {
tot = someNums[x];
sum = sum + someNums[x];
}
Hope this helps
You want to iterate while x is lesser than someNums.length; since max index in array is arraysLength - 1, so change x <= someNums.length; to x < someNums.length; in for loop
There is no need for tot (I assume it should store total numbers) variable because you already have someNums.length which represents how many numbers you summed. BTW you already are calculating avg using sum and someNums.length. So you can safely remove
tot = someNums[x];
from your code.
What you did is you looped beyond the scope of the array. Try doing someNums.length, you will get the number 5.
Going to your for loop we now know that it starts at 0 and increments until it gets to 5. And the for loop is traversing over the array and is pointing at the positions in your array.
So let's traverse through your loop.
At x = 0, someNums[x] = 4.
At x = 1, someNums[x] = 17,
At x = 2, someNums[x] = 22,
At x = 3, someNums[x] = 8,
At x = 4, someNums[x] = 35,
As you can see, your array has now ended, you no longer have any more elements to traverse over. But we have previously stated that your for loop increments until it gets to 5.
So at x = 5, someNums[x] will have to give you an error since you are pointing at a position and trying to retrieve information from that position that essentially does not exist.
There are two ways to solve your problem:
You change the loop to for(int x = 0; x < someNums.length; x++)
You change the loop to for(int x = 0; x <= someNums.length - 1; x++)
These will solve your problem because they will stop your loop at 4 and not at 5, therefore you will no longer receive an error.