ArrayIndexOutOfBoundsException question

J

Johan

Hi,

This is mayby a simple question, but why do I get an
ArrayIndexOutOfBoundsException after the last question?

.....

String[] questions = { "Question 1", "Question 2", "Question 3",
"Question 4", "Question 5" } ;
String[] data = new String[4];

.....

for (int i = 0; i < counter ; ++i) {
System.out.println(questions);
try {
data = br.readLine(); //I get the exception here according to the
debugger in Eclipse
} catch (IOException e) {
e.printStackTrace();
}
}

What I was trying to do was ask 5 questions and store the replys in
another array and insert them later on in an database.

Does anyone have an suggestion about how to solve this?

tia

Johan
 
G

Gordon Beaton

This is mayby a simple question, but why do I get an
ArrayIndexOutOfBoundsException after the last question?

There are 5 questions, but 'data' has only space for 4 Strings.

/gordon
 
D

Darryl L. Pierce

Johan wrote:

What I was trying to do was ask 5 questions and store the replys in
another array and insert them later on in an database.

Then why are you only allocating space for 4 answers with the line:

String[] data = new String[4];

?
 
C

Chris Riesbeck

Gordon Beaton said:
There are 5 questions, but 'data' has only space for 4 Strings.

And the way to avoid that problem is avoid hardwired numbers. E.g.,

String[] questions = { "Question 1", "Question 2", ... };
String[] data = new String[questions.length];
 
P

Paul Lutus

Johan said:
Hi,

This is mayby a simple question, but why do I get an
ArrayIndexOutOfBoundsException after the last question?

....

String[] questions = { "Question 1", "Question 2", "Question 3",
"Question 4", "Question 5" } ;
String[] data = new String[4];

Yipes. Try this robust solution (allows you to add strings without thinking
about the side effects):

String[] questions = { "Question 1", "Question 2", "Question 3",
"Question 4", "Question 5" } ;

String[] data = new String[questions.length];

or: 4 != 5
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top