loop prematurely quitting
This loop works fine but prematurely quits at times. I set a piece of code in it so th开发者_如何学JAVAat I can view the random number. It only closes prematurely when the random number is equal to the highest numbered question the user inputs
(Example...a user wants 10 questions, if the random number is 10 the program quits.)
I have no idea why since i have it set to if(random number <= the number of questions)
for ( int loop = 1; loop < loopCount; loop++ )
{
aa = r.nextInt ( 10 + 1 );
abc = ( int ) aa;
String[] userAnswer = new String[x];
JOptionPane.showMessageDialog ( null, abc );
if ( abc <= x )
{
for ( overValue = 1; overValue < forLoop; overValue++ );
{
userAnswer[j] = JOptionPane.showInputDialog ( null, "Question " + quesNum + "\n" + questions[abc] + "\n\nA: " + a[abc] + "\nB: " + b[abc] + "\nC: " + c[abc] + "\nD: " + d[abc] );
if ( userAnswer[j].equals ( answers[j] ) )
{
JOptionPane.showMessageDialog ( null, "Correct. \nThe Correct Answer is " + answers[abc] );
}
else
{
JOptionPane.showMessageDialog ( null, "Wrong. \n The Correct Answer is " + answers[abc] );
}//else
}//for
}//if
}//for
It seems that you may have an array out of bounds at the last line shown:
String[] userAnswer = new String[x];
JOptionPane.showMessageDialog(null,abc);
if(abc <= x)
{
for(overValue = 1; overValue < forLoop; overValue++);
{
... questions[abc] ... a[abc] ... b[abc] ... c[abc] ... d[abc] ...
If the arrays questions
, a
, b
, c
or d
are of size x
(as userAnswer
is), indexing them with x
causes such an exception.
You should have a condition of
if(abc < x)
and preferably you should also adjust the random generation:
aa = r.nextInt ( x );
You mean the outer for loop:
for (int loop = 1; loop < loopCount; loop++) {
or the inner for loop
for (overValue = 1; overValue < forLoop; overValue++);
Both the for loop has problem because the initial number should be 0 not be 1. And another problem is that the second for loop end with ;, so it will not do anything at all
Your problem is that array indices start from 0 and go to length-1. If the length is x
, the highest index is x-1
, so when the input is exactly x
and you try to index into the array, it will fail.
The condition should be abc < x
I'm not sure where you've got forLoop and loopCount from, but it looks like the for loops are off-by-one. I'd usually write either for(x=0;x<X;x++) or for(x=1;x<=X;x++).
I don't think this is your actual problem, but it's something to check.
精彩评论