Array Index out of range exception - java

I want to print out the elements of this multidimensional array but I get the index out of range error.
public class test {
public static void main(String[] args) {
int array1[][]={{1,2,3,4},{5},{6,7}};
for (int i=0; i<3;i++){
for (int j=0; j<4;j++){
System.out.println(array1[i][j]);
}
}
}
}

The problem is that with the loop, written like this, you assume that the nested arrays are all of length of 4 (and they are not). You'd better do:
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}

Yes, because the second "subarray" doesn't have 4 elements. It would be better to do this dynamically:
// Note preferred syntax for array types - keep all the type info in one place.
int[][] array1 = {{1,2,3,4},{5},{6,7}};
for (int i = 0; i < array1.length; i++) {
for (int j = 0; array1[i].length; j++) {
System.out.println(array1[i][j]);
}
}
This way the iteration count of the inner loop depends on the array being iterated over.
An alternative is to use the enhanced for loop:
for (int[] subarray : array1) {
for (int value : subarray) {
System.out.println(value);
}
}

2 points regarding the following solution (and the other similar answers):
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
Here it wont make much difference, as the code is very short, but for better performance you should always avoid repeated calculations if the result never changes. array1's length wont change so calculating its length every iteration is not efficient. This would be improved solution.
int array1Length = array1.length;
for (int i=0; i < array1Length;i++){
int array1InnerLength = array1[i].length;
for (int j=0; j < array1InnerLength;j++){
...
}
}
Some people may suggest using ++j / ++i instead of i++ and j++ for better performance, you can read more about it here: What is the difference between ++i and i++?. Its not that critical imo, but it improves understanding of the code you're writing.

Related

ArrayIndexOutOfBounds Exception in for loop when trying to parse data

I'm working on a code for a requirement. If for example I have this test data:
multiple variable:
3
Context Change (next in array)
1
Context Change (next in array)
2
Repeat variable:
TESTA
Context change (next in array)
TESTB
Context change (next in array)
TESTC
Code:
I've tried using j as the array. Both i and j are failing since if for example i is 3 in the 1st array, then multiple[i] will be multiple[3] which is out of bounds already.
for(int j=0; j <= multiple.length - 1; j++) {
for(int i=0; i < Integer.parseInt(multiple[i]); i++) {
result.addValue(Repeat[i]);
}
}
Output should be this one:
TESTA
TESTA
TESTA
Context change (next in array)
TESTB
Context change (next in array)
TESTC
TESTC
This is the only thing wrong about your code with a first look:
for(int j = 0; j <= multiple.length - 1; j++) {
for(int i = 0; i < Integer.parseInt(multiple[j]); i++) {
result.addValue(Repeat[i]);
}
}
You should be using multiple[j] instead of multiple[i] since your are looping in that loop. Other thing is why are you doing multiple.length - 1? Also please clarify what you want to do because your answer doesn't make that much sense, at least to me. What are you trying to do? If this helps, than great! Otherwise clarify the problem. Hope it helps.
I don't understand what you are asking for, but I guess you're asking the question about multidimensional arrays traversal.
this is the code for example, maybe can help you:
int[][] arr = {{23, 45, 123}, {545}, {124,543}};
for (int i = 0; i < arr.length; i++) {
System.out.println("-------" + i + "-------");
for (int j = 0; j < arr[i].length; j++) {
System.out.println(arr[i][j]);
}
}

Different ways to iterate 2 dimensional array

I'm preparing for the Java OCA exam but there are several tricky questions about how iterates a multidimensional array.
So, if I had this array and I wanted to iterate using the for and for-each loops what would all be ways to do it?
I usually used only these three:
int [][]matrix = {{3,4,5},{6,7,8},{9},{10,11,12}};
//First way
for (int [] a : matrix){
for (int i =0; i<a.length;i++){
//code
}
}
//Second way
for (int []a: matrix){
for (int i: a){
//code
}
}
//Third way
for (int i = 0; i<matrix.length; i++) {
for (int j=0; j<matrix[a].length; j++) {
//code
}
}
//Fourth way???
Thanks a lot!
You missed the for, foreach combination:
for (int i = 0; i<matrix.length; i++) {
for (int j: matrix[i]){
// code
}
}
You can also use while loops instead of for. Can you be more specific about the context, so we can help you properly with what you need?

How to change all elements in a 2D Array to the same value using for loops in java

This is my first time asking a question here, so forgive me if my formatting is a little sloppy.
I need to know how to set all the elements of a 2D Array to the same value, using for loops, with Java.
I was able to get this far:
import java.util.Arrays;
public class TheArray{
public static void main (String[] args){
int[][] pixels = new int[768][1024];
for(int i = 0; i < pixels.length; i++){
for(int j = 0; j < pixels[i].length; j++){
Arrays.fill(pixels[i], 867);
}
}
}
}
However I have no idea if I have done it right. So all I want it to do is make all of the elements of the 2D array be 867.
You don't need to use Arrays.fill if you're already using for loops. Just do:
for(int i = 0; i < pixels.length; i++){
for(int j = 0; j < pixels[i].length; j++){
pixels[i][j] = 867;
}
}
Arrays.fill would be used instead of the inner for loop.
Use the following line inside your loop:
pixels[i][j] = 867;

ArrayList of ArrayLists - clear function confusion

Here is a particular method I have written:
class A {
private static ArrayList<ArrayList<Integer>> inputTerms = new ArrayList<ArrayList<Integer>();
public static void method1(ArrayList<Integer> terms) {
ArrayList<Integer> clauses = new ArrayList<Integer>();
int N = terms.size();
for (int i = 0; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
clauses.clear();
}
}
}
}
This method is called multiple times from the main function.
In the end, i try to write the contents of the class variable into a file. However, when I do this, i get 0 as the contents of inputTerms. However, if i remove the clauses.clear() line, i am able to get approppriate values.
My program is such that it is vital for me to clear the clauses after adding to inputTerms. Is there any alternative to this?
**Hmmm.. I have done what you've suggested. However, I haven't quite overcome the problem. To give more background, in my main function, I have the following code:
for (int i=0; i<N-1; i++){
ArrayList<Integer> firstdiagonalTerms = new ArrayList<Integer>();
for (int j=0; j<N-i; j++){
firstdiagonalTerms.add(variable[j][i+j]);
}
method1(firstdiagonalTerms);
}
I have to call the method1 function 4 times for different combinations of 'i' and 'j'. However, I still get 0 when I use the above mentioned suggestions**
You are adding the same list and clearing it repeatedly. When you add an object to a list it copies a reference to it, not a copy of the object.
int N = terms.size();
for (int i = 0; i < N - 1; i++) {
for (int j = i + 1; j < N; j++) {
List<Integer> clauses = new ArrayList<Integer>();
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
}
}
or
for (int i = 0, N = terms.size(); i < N - 1; i++)
for (int j = i + 1; j < N; j++)
inputTerms.add(Arrays.asList(-terms.get(i), -terms.get(j)));
Not sure i understand what you are trying to achieve, but you keep reusing the same list, which is probably not what you meant to do.
You should probably move the ArrayList<Integer> clauses = new ArrayList<Integer>(); inside the inner loop, and not call clauses.clear() at all.
When you are adding "clauses" you are adding the actual object to the arrayList, not a copy. So when you clear them all the values in the list will be removed. To get arround this, add a clone of the list:
inputTerms.add((ArrayList<Integer>) clauses.clone());
When you call clear() on list, you are updating/removing same objects (because list contains reference to objects, not copy of object). That is what causing the issue.
I think you need to do something like below. Instead of using clear(), create a new list everytime.
public static void method1 (ArrayList<Integer> terms)
{
int N = terms.size();
for (int i = 0; i<N-1; i++) {
for (int j=i+1; j<N; j++) {
ArrayList<Integer> clauses = new ArrayList<Integer>();
clauses.add(-terms.get(i));
clauses.add(-terms.get(j));
inputTerms.add(clauses);
}
}

set() in ArrayList

I am new to Java, please help me.
My program is
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("a");
al.add("b");
for(int i=1;i<=10;i++)
{
al.add(i);
}
al.remove("a");
al.set(1,"c");
for(int j=3;j<=al.size();j++)
{
al.set(j,"z");
}
System.out.println(al);
}
};
in above any mistake........plz help me
a) You need to make the class public to run it:
public class Test
{
b) the last semi-colon is a syntax error No it's not, it's just unnecessary noise.
c) This fails with an IndexOutOfBoundsException:
for(int j = 3; j <= al.size(); j++){
al.set(j, "z");
}
It needs to be:
for(int j = 3; j < al.size(); j++){
al.set(j, "z");
}
Explanation: List Indexes are zero-based, so the highest position in a List with n elements is n-1
BTW, the above code can be written in a more elegant way like this:
Collections.fill(al.subList(3, al.size()), "z");
Reference:
Collections.fill(List<T>, T)
List.subList(from, to)
This code will throw an IndexOutOfBounds exception because of the line:
for (int j = 3; j <= al.size(); j++) {
to fix it, you need to change it to:
for (int j = 3; j < al.size(); j++) {
This is because the <= means that your for loop iterates over the end of the list.
List~ and Arrayindices start at 0, not 1. So if you have a list of 3 Elements, they go from index: 0, 1, 2. So you normally iterate from (i = 0; i < list.size (); ++i). Less than, not less/equal.
for (int j=3; j < al.size (); j++)
1.The semicolon in the last line
2.change the code from
for(int j=3;j<=al.size();j++)
to
for(int j=3;j<al.size();j++)
Arraylist are always accessed from from 0th index to less than the size of the array.
I think it is necessary to change also the start index from 3 to 2:
for (int j=2; j < al.size (); j++)

Categories