0

Today I wanted to use the java code below and it did not work of course. I know that in order to process the idea below I should create a basic array which should include all my String variables but... I am wondering is there an option to change my code and process the code without the mentioned basic array ?

ArrayList<String> array = new ArrayList<String>();

String variable1 = "text1";
String variable2 = "text2";
String variable3 = "text3";

for ( int i = 1; i <= 3; i++ ){
array.add(i, variable + i ); // error 
}

thank you in advance !

5
  • What's wrong with just array.add("text1")? Commented Apr 12, 2016 at 20:32
  • 1
    variable1, variable2, and variable3 should just be an array (variable[]). I see what you are trying to do with variable+i, but it will not do what you are wanting. You want to use an array. Commented Apr 12, 2016 at 20:32
  • You are trying to add at index i (which is first 1), hence the error. Commented Apr 12, 2016 at 20:34
  • IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())... index here is 1 and size 0. Commented Apr 12, 2016 at 20:34
  • My comments assume "variable" does exists in your code (and is probably equals to "text" and that variable1,2,3 are there to help point what you are trying to achieve. Commented Apr 12, 2016 at 20:36

1 Answer 1

0

This is the only reasonable way, if we ignore fact that your array is already a collection.

ArrayList<String> array = new ArrayList<String>();

String[] variables=new String[3];
variables[0] = "text1";
variables[1] = "text2";
variables[2] = "text3";

for ( int i = 0; i < 3; i++ ){
    array.add(variables[i]); // error 
}
Sign up to request clarification or add additional context in comments.

2 Comments

String variables[0]?
@AndyTurner ahh yes my mistake. You could simply edit the post IMHO :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.