Hafsa Izhar
Hafsa Izhar

Reputation: 1

I have having Array Index Out Of Bound Error in this code

HERE IS THE JAVA CODE.HAVING ARRAY INDEX OUT OF BOUND ERROR ON RUNTIME. i don't know what to do. I have tried every possible solution for this. This is the error i am getting "Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1 at QuizPG1.(QuizPG1.java:90) at QuizPG1$3.run(QuizPG1.java:330)"

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.table.DefaultTableModel;


public class QuizPG1 extends javax.swing.JFrame {
      String questions[][]=new String [10][5];
      String answers [][]=new String [10][1];
      String userans[][]=new String[10][1];
      public static int timer = 15;
      public static int answerGiven = 0;
      public static int count = 0;
      public static int score = 0;
      String name;
    public QuizPG1(String name) {
        this.name = name;
        initComponents();
        setSize(950,750);
        setLocation(500,150);
        
        questions[0][0]="What is the general purpose of JAVA VIRTUAL MACHINE(JVM)?";
        questions[0][1]="Compile Java Code";
        questions[0][2]="Execute Java Code";  //correct 
        questions[0][3]="Debug Java Code";
        questions[0][4]="Package Java Code";
        
        questions[1][0]="Which keyword is used to define constant variable in JAVA?";
        questions[1][1]="final";   //correct
        questions[1][2]="const";
        questions[1][3]="var";
        questions[1][4]="static";
        
        
        questions[2][0]="In JAVA which access modifier provides the widest visibility?";
        questions[2][1]="private";
        questions[2][2]="default";
        questions[2][3]="protected";
        questions[2][4]="public";  //correct
        
        questions[3][0]="Which is the correct syntax to create an object of a class named 'My Class'?";
        questions[3][1]="object MyClass = new object;";
        questions[3][2]="MyClass obj = create MyClass();";
        questions[3][3]="MyClass obj = new MyClass();";   //correct
        questions[3][4]="object obj = new MyClass;";
        
        questions[4][0]="Which data type is used to store a single Unicode character in JAVA?";
        questions[4][1]="char";  //correct
        questions[4][2]="string";
        questions[4][3]="character";
        questions[4][4]="unicode";
        
        questions[5][0]="Which statement is used to exit a loop in JAVA?";
        questions[5][1]="halt";
        questions[5][2]="stop";
        questions[5][3]="end";
        questions[5][4]="break";  //correct
        
        questions[6][0]="Which of the following is not a primitive data type in JAVA?";
        questions[6][1]="int";
        questions[6][2]="float";
        questions[6][3]="boolean";
        questions[6][4]="object";  //correct
        
        questions[7][0]="Which JAVA loop is guaranteed to execute at least once?";
        questions[7][1]="while";
        questions[7][2]="do-while";  //correct
        questions[7][3]="for";
        questions[7][4]="for-each";
        
        questions[8][0]="Which method is called automatically when an object is created from a class?";
        questions[8][1]="start()";
        questions[8][2]="initialize()";
        questions[8][3]="main()";
        questions[8][4]="constructor()";  //correct

        
        questions[9][0]="Which JAVA keyword is used to explicitly raise an exception?";
        questions[9][1]="raise";
        questions[9][2]="throw";   //correct
        questions[9][3]="exception";
        questions[9][4]="try";   
        
        answers[0][1]="Execute Java Code";
        answers[1][1]="final";
        answers[2][1]="public";
        answers[3][1]="MyClass obj = new MyClass();";
        answers[4][1]="char";
        answers[5][1]="break";
        answers[6][1]="object";
        answers[7][1]="do-while";
        answers[8][1]="constructor()";
        answers[9][1]="throw";
        
        buttonGroup1.add(opt1);
        buttonGroup1.add(opt2);
        buttonGroup1.add(opt3);
        buttonGroup1.add(opt4);
        submit.setEnabled(false);
        add(submit);
        start(count);
        setVisible(true);
        
    }

    QuizPG1() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
 private void nextActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
     //   DefaultTableModel tb = (DefaultTableModel) tablemodel1.getModel();
        repaint();
        
        answerGiven = 1;
        if (buttonGroup1.getSelection()== null){
               userans[count][0]="";
           }else{
               userans[count][0]=buttonGroup1.getSelection().getActionCommand();
           }
        if(count == 8){
            next.setEnabled(false);
            submit.setEnabled(true);
        }
        count++;
        start(count);
    }                                    

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        
        answerGiven = 1;
        if (buttonGroup1.getSelection()==null){
               userans[count][0]="";
           }else{
               userans[count][0]=buttonGroup1.getSelection().getActionCommand();
           }
             for(int i=0 ; i<userans.length;i++){
                 if(userans[i][0].equals(answers[i][1])){
                     score += 10;
                 }
             }
             setVisible(false);
             new Score(name,score);
             //SCOREtf.setText(score);
                 
    }                                      

    /**
     * @param args the command line arguments
     */
    public void paint(Graphics g){
        super.paint(g);
        
        String time = "Time Left:"+ timer + "seconds";
        g.setColor(Color.RED);
        g.setFont(new Font("Tahoma",Font.BOLD,25));
        if (timer > 0){
           g.drawString(time, 900, 500);    
        }else{
            g.drawString("Times Up!!", 900, 500);   
        }
       timer--;
       
       try{
           Thread.sleep(1000);
           repaint();
       }  catch (InterruptedException ex) {
              Logger.getLogger(QuizPG1.class.getName()).log(Level.SEVERE, null, ex);
          }
       if (answerGiven == 1){
           answerGiven = 0;
           timer = 15;
       }else if (timer < 0) {
           
           if(count == 8){
            next.setEnabled(false);
            submit.setEnabled(true);
         } 
           if(count == 9){  //submit button
               if(count < userans.length){
             if (buttonGroup1.getSelection()==null){
               userans[count][0]="";
           }else{
               userans[count][0]=buttonGroup1.getSelection().getActionCommand();
           }
       }
              
             for(int i=0 ; i<userans.length;i++){
                 if(userans[i][0]!= null && userans[i][0].equals(answers[i][1])){
                     score += 10;
                 }
             }
             setVisible(false);
              new Score(name,score);
         } else{      // next button
           
           if (buttonGroup1.getSelection()==null){
               userans[count][0]="";
           }else{
               userans[count][0]=buttonGroup1.getSelection().getActionCommand();
           }
           count++;
           start(count); 
           }
       }
    
    }
   
    public void start(int count){
        qno.setText(""+ (count +1)+".");
        question.setText(questions[count][0]);
        opt1.setText(questions[count][1]);
        opt1.setActionCommand(questions[count][1]);
        
        opt2.setText(questions[count][2]);    
        opt2.setActionCommand(questions[count][2]);
        
        opt3.setText(questions[count][3]);        
        opt3.setActionCommand(questions[count][3]);
        
        opt4.setText(questions[count][4]);
        opt4.setActionCommand(questions[count][4]);
        
        buttonGroup1.clearSelection();
    }
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(QuizPG1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(QuizPG1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(QuizPG1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(QuizPG1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new QuizPG1("user").setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton next;
    private javax.swing.JRadioButton opt1;
    private javax.swing.JRadioButton opt2;
    private javax.swing.JRadioButton opt3;
    private javax.swing.JRadioButton opt4;
    private javax.swing.JLabel qno;
    private javax.swing.JLabel question;
    private javax.swing.JButton submit;
    // End of variables declaration                   
}

I tried this piece of code in paint method.

for(int i = 0; i < userans.length; i++){
    if(userans[i][0] != null && userans[i][0].equals(answers[i][1])){
        score += 10;
    }
}```

But it is still giving error.So i removed that amendment from my original code. Please provide me the solution.
The program is simple but on runtime I am having the Array index out of bound error.

Upvotes: 0

Views: 101

Answers (0)

Related Questions