ArrayIndexOutOfBounds Exception in for loop when trying to parse data - java

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]);
}
}

Related

Take a word and print it out in the shape of a triangle as shown below - Parameters and methods

Thanks for taking the time to check out my question. I have to write some code in Dr. Java that takes in a word and then prints it out in a specific pattern. Basically here are some examples:
Input: fishy
Output: f
fifi
fisfisfis
fishfishfishfish
fishyfishyfishyfishyfishy
Basically, I'm just adding another character to the previous one and printing it out that many number of times.
Here is my attempt at my solution:
String wordcopy = word;
int size = wordcopy.length();
for (int i=1; i<=size; i+=1)
{
for (int j=0; j<i; j++)
{
System.out.print(word.substring(0,j+1));
}
System.out.println("");
}}
I have already set up my parameters so that's fine. The only thing I seem to be missing is the method itself that prints out what it's supposed to. Can anyone please help me with this problem and how I can go from here?
Thanks!
Replace word.substring(0,j+1) with word.substring(0,i):
String wordcopy = word;
int size = wordcopy.length();
for (int i = 1; i <= size; i += 1) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}
There are some cleanup things you can do. For instance, this code yields the same result:
for (int i = 1; i <= word.length(); i++) {
for (int j = 0; j < i; j++) {
System.out.print(word.substring(0, i));
}
System.out.println("");
}

Array Index out of range exception

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.

Array List Loop Out of Bounds

I've got this code which I am developing below. I want to loop through two array lists, the first list I want to look at every entry, the second I only want to look at every 3rd entry and see if they match. If they do match then I want to compare the other two entries on the 2nd list. The problem with the code lies in the "int result1 = " line, I can't understand why it would say out of bounds. Any help much appreciated!
for (int i = 0; i < array1.size(); i++){
for (int j = 3; j <array2.size(); j = j + 3) {
if ((array1.get(i)).equals(array2.get(j-3))){
int result1 = array2.get(j-1).compareTo(array2.get(j-2));
}
}
}
This is an extended comment, not an answer.
It is clear that the posted code cannot produce the stated exception. There is something else going on. You need to prepare a Simple, Self-Contained, Correct Example that produces the exception. Here is an example of a program based on the code you posted that does not reproduce the problem. You need to post something similar, but with enough of your actual code to get the exception.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> array1 = new ArrayList<Integer>();
List<Integer> array2 = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
array1.add(0);
array2.add(0);
}
int result = 0;
for (int i = 0; i < array1.size(); i++) {
for (int j = 3; j < array2.size(); j = j + 3) {
if ((array1.get(i)).equals(array2.get(j - 3))) {
int result1 = array2.get(j - 1).compareTo(array2.get(j - 2));
result += result1;
}
}
}
System.out.println(result);
}
}

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