此循环工作正常,但有时会过早退出。我在其中设置了一段代码,以便可以查看随机数。它仅在随机数等于用户输入的最高编号的问题时过早关闭

(示例...用户想要10个问题,如果随机数为10,程序将退出。)

我不知道为什么,因为我将其设置为if(随机数

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

最佳答案

似乎在显示的最后一行中可能有一个超出范围的数组:

            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] ...


如果数组questionsabcd的大小为x(如userAnswer一样),则用x对其进行索引会导致此类异常。

您应该具备以下条件

            if(abc < x)


最好还应调整随机数:

aa = r.nextInt ( x );

10-07 12:01