2014-11-24 2 views
0

Я пытаюсь создать 10 вопросов с вопросом выбора с использованием массивов. Я очень новичок, так что медведь со мной. В настоящее время я могу получить окно для заполнения, с названием и кнопками, которые я установил. Кнопки ничего не делают, и вопросы с выборами не заполняются. Кажется, что когда я вызываю класс к основному методу, он вызывает только конструктор. Я не совсем уверен, где я ошибаюсь. У меня есть массив для моих вопросов с выбором и массив, у которого есть вопрос и правильный ответ. Пожалуйста помоги. Я работал над этим в течение 4 дней.java quiz только доступ к конструктору

первый файл наборы данных:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.event.*; 
import java.util.*; 

class Test2 extends JFrame implements ActionListener 

{ 
    JPanel panel; 
    JPanel panelresult; 
    JRadioButton choice1; 
    JRadioButton choice2; 
    JRadioButton choice3; 
    JRadioButton choice4; 
    ButtonGroup bg; 
    JLabel question; 
    JButton next; 
    String[][] questions; 
    String[][] choices; 
    int qaid; 
    HashMap<Integer,String>map; 

    public Test2() 
    { 

     setTitle("Tennis Quiz"); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setSize(430,350); 
     setLocation(300,100); 
     setResizable(false); 
     Container cont = getContentPane(); 
     cont.setLayout(null); 
     cont.setBackground(Color.GRAY); 
     bg = new ButtonGroup(); 
     choice1 = new JRadioButton("A"); 
     choice2 = new JRadioButton("B"); 
     choice3 = new JRadioButton("C"); 
     choice4 = new JRadioButton("D"); 
     bg.add(choice1); 
     bg.add(choice2); 
     bg.add(choice3); 
     bg.add(choice4); 
     question = new JLabel("Choose a correct answer"); 
     question.setForeground(Color.BLUE); 
     question.setFont(new Font("Aria", Font.BOLD, 11)); 
     next = new JButton("Next"); 
     next.setForeground(Color.GREEN); 

     panel = new JPanel(); 
     panel.setBackground(Color.LIGHT_GRAY); 
     panel.setLocation(10,10); 
     panel.setSize(400,300); 
     panel.setLayout(new GridLayout(6,2)); 
     panel.add(question); 
     panel.add(choice1); 
     panel.add(choice2); 
     panel.add(choice3); 
     panel.add(choice4); 
     panel.add(next); 
     cont.add(panel); 
     setVisible(true); 
     qaid = 0; 
     setData(); 

     String readqaId = readqaId(qaid);     
    } 

    public void actionPerformed(ActionEvent e) 
    { 
     switch (next.getText()) { 
      case "Next": 
       if(qaid<9) 
       { 
        map.put(qaid,getSelection()); 
        qaid++; 
        readqaId(qaid); 
       } 
       else 
       { 
        map.put(qaid,getSelection()); 
        next.setText("Show answers"); 
       }  break; 
      case "Show answers": 

       break; 
     } 
    } 

    public String setData() 
    { 
     questions = new String[10][5]; 

     questions[0][0] = "Who is world's number one on the ATP Tennis tour?"; 
     questions[0][1] = "Del Potro"; 
     questions[0][2] = "Nadal"; 
     questions[0][3] = "Djockovic"; 
     questions[0][4] = "Federer"; 

     questions[1][0] = "Who is world's number one on the WTA Tennis tour?"; 
     questions[1][1] = "Venus Williams"; 
     questions[1][2] = "Serenca Williams"; 
     questions[1][3] = "Simona Halep"; 
     questions[1][4] = "Svetlana Kuznetsova"; 

     questions[2][0] = "Who has the fastest serve?"; 
     questions[2][1] = "Andy Roddick"; 
     questions[2][2] = "Milos Roanic"; 
     questions[2][3] = "Leyton Hewitt"; 
     questions[2][4] = "Juan Martin Del Potro"; 

     questions[3][0] = "Who holds the most titles on the mens tour?"; 
     questions[3][1] = "Roger Federer"; 
     questions[3][2] = "Raphael Nadal"; 
     questions[3][3] = "Novak Djokovack"; 
     questions[3][4] = "Andy Murray"; 

     questions[4][0] = "Who holds the most titles on the womens tour?"; 
     questions[4][1] = "Chris Evert"; 
     questions[4][2] = "Billie Jean King"; 
     questions[4][3] = "Martina Navratilova"; 
     questions[4][4] = "Serena Williams"; 

    questions[5][0] = "Which male tennis player has won the most majors?"; 
    questions[5][1] = "Donald Young?"; 
    questions[5][2] = "Raphal Nadal?"; 
    questions[5][3] = "Roger Federer?"; 
    questions[5][4] = "Pete Sampras"; 

    questions[6][0] = "Which male tennis player won the U.S. Open in 2014"; 
    questions[6][1] = "Roger Federer"; 
    questions[6][2] = "Lleyton Hewitt"; 
    questions[6][3] = "Rafael Nadal"; 
    questions[6][4] = "Marian Celic"; 

    questions[7][0] = "Which female tennis player has won all 4 Grand Slams?"; 
    questions[7][1] = "Venus Williams"; 
    questions[7][2] = "Svetlana Kuznetsova"; 
    questions[7][3] = "Caroline Wozniacki"; 
    questions[7][4] = "Serena Williams"; 

    questions[8][0] = "Which male tennis player won the French Open in 2014"; 
    questions[8][1] = "Roger Federer"; 
    questions[8][2] = "Raphael Nadal"; 
    questions[8][3] = "Milos Roanic"; 
    questions[8][4] = "Gael Monfils"; 

    questions[9][0] = "Which female tennis player won the French Open in 2014?"; 
    questions[9][1] = "Venus Williams"; 
    questions[9][2] = "Serena Williams"; 
    questions[9][3] = "Caroline Wozniacki"; 
    questions[9][4] = "Maria Sharapova"; 

    choices = new String[10][2]; 
    choices[0][0] = "Who is world's number one on the ATP Tennis tour?"; 
    choices[0][3] = "Djockovic"; 

    choices[1][0] = "Who is world's number one on the WTA Tennis tour?"; 
    choices[1][2] = "Serenca Williams"; 

    choices[2][0] = "Who has the fastest serve?"; 
    choices[2][2] = "Milos Roanic"; 

    choices[3][0] = "Who holds the most titles on the mens tour?"; 
    choices[3][1] = "Roger Federer"; 

    choices[4][0] = "Who holds the most titles on the womens tour?"; 
    choices[4][3] = "Martina Navratilova"; 

    choices[5][0] = "Which male tennis player has won the most majors?"; 
    choices[5][3] = "Roger Federer?"; 

    choices[6][0] = "Which male tennis player won the U.S. Open in 2014"; 
    choices[6][4] = "Marian Celic"; 

    choices[7][0] = "Which female tennis player has won all 4 Grand Slams?"; 
    choices[7][4] = "Serena Williams"; 

    choices[8][0]= "Which male tennis player won the French Open in 2014"; 
    choices[8][2] = "Raphael Nadal"; 

    choices[9][0] = "Which female tennis player won the French Open in 2014?"; 
    choices[9][4] = "Maria Sharapova"; 

    map = new HashMap<>(); 
    return null;   
} 

public String getSelection() 
{ 
    String selectedChoice = null; 
    Enumeration<AbstractButton> buttons=bg.getElements(); 
    while(buttons.hasMoreElements()) 
    { 
     JRadioButton temp = (JRadioButton)buttons.nextElement(); 
     if(temp.isSelected()) 
     { 
      selectedChoice = temp.getText(); 
     } 
    } 
    return(selectedChoice); 
} 

private String readqaId(int qaid) 
{ 
    question.setText("" + questions[qaid][0]); 
    choice1.setText(choices[qaid][1]); 
    choice2.setText(choices[qaid][2]); 
    choice3.setText(choices[qaid][3]); 
    choice4.setText(choices[qaid][4]); 
    choice1.setSelected(true); 
    return null;   
} 

public void reset() 
{ 
    qaid = 0; 
    map.clear(); 
    readqaId(qaid); 
    next.setText("Next"); 
} 

public int calCorrectAnswer() 
{ 
    int qnum = 10; 
    int count = 0; 
    for(int qid = 0; qid<qnum;qid++) 
    if(choices[qid][1].equals(map.get(qid))) 
     count++; 
    return count; 
} 

public class Report extends JFrame 
{ 
    Report() 
    { 
     setTitle("Answers"); 
     setSize(850,550); 
     setBackground(Color.WHITE); 
     addWindowListener(new WindowAdapter() 
       { 
        public void windowClosing(WindowEvent e) 
        { 
         dispose(); 
         reset(); 
        } 
        }); 
       Draw d = new Draw(); 
       add(d); 
       setVisible(true); 
       } 
    class Draw extends Canvas 
    { 
     public void paint(Graphics g) 
     { 
      int qnum = 10; 
      int x = 10; 
      int y = 20; 
      for(int i = 0; i<qnum;i++) 
      { 
      g.setFont(new Font("Aria", Font.BOLD, 12)); 
      g.drawString(i+1+"." + choices[i][0], x, y); 
      y+=30; 
      g.setFont(new Font("Aria", Font.PLAIN, 12)); 
      g.drawString("Correct Answer"+choices[i][1], x, y); 
      y+=30; 
      g.drawString(" Your answer" + map.get(i), x, y); 
      y+=30; 
      if(y>400) 
      { 
      y = 20; 
      x = 450; 
      } 


      } 
      int numc=calCorrectAnswer(); 
      g.setColor(Color.BLUE); 
      g.setFont(new Font("Aria", Font.BOLD,14)); 
      g.drawString("Number of correct answers." + numc, 300, 500); 

     } 
    } 
    } 
} 

второй файл тянет первый файл:

import java.util.Arrays; 

public class QuizProgram 
{ 
    public static void main(String args[]) 
    { 
     Test2 test2 = new Test2(); 
    } 

} 
+0

я назвал метод SetData() вместо переменной и удаляется вопрос 10, который находится за пределами параметров массива. Мой вызов метода - это советы по методу езды в конструкторе. Все еще не отображает данные. – New2Java

ответ

2

Я вижу некоторые проблемы:

  1. Вы не вызывая setData метод, так что вы не инициализирует свои массивы. Вместо этого вы объявляете переменную с тем же именем - String setData;
  2. Если вы звонили setData, вы получили бы ArrayIndexOutOfBoundsExcpetion, так как массив из 10 элементов имеет только индексы от 0 до 9. Вы должны правильно инициализировать свои массивы: questions = new String[11][5]; и choices = new String[11][2];. Либо это, либо вы должны удалить один вопрос.
  3. У вас также есть ошибка в readqaId. Вы берете выбор из неправильного массива.

Это должно быть:

private String readqaId(int qaid) 
{ 
    question.setText("" + questions[qaid][0]); 
    choice1.setText(questions[qaid][1]); 
    choice2.setText(questions[qaid][2]); 
    choice3.setText(questions[qaid][3]); 
    choice4.setText(questions[qaid][4]); 
    choice1.setSelected(true); 
    return null; 
} 
+0

Я удалил вопрос 10. Как я могу назвать свою setData вместо объявления переменной? – New2Java

+0

@ New2Java 'setData()'. BTW, похоже, что вам не нужно возвращаемое значение этого метода, поэтому вы можете изменить его на void. – Eran

+0

когда я вызываю setData(), я получаю overridable метод в конструкторе. Я изменил setData() на void. К сожалению, пока не отображается setData() на панели. Извините, здесь я полностью в тупике. – New2Java

3

вы определили

 questions = new String[10][5]; 

, а затем

 questions[10][0] = "What size is a tennis ball?"; 
    questions[10][1] = "2.57 - 2.70 inches"; 
    questions[10][2] = "3 - 4 inches"; 
    questions[10][3] = "1 - 2 inches"; 
    questions[10][4] = "5-6 inches"; 

вы не можете получить доступ к индексу 10 вопросов при определении его длины 10.

+1

Согласен. Когда вы определяете массив в java, значение представляет собой количество элементов, а не индекс max, поэтому, если вы определяете 10, они будут от 0 до 9. У вас есть 11 вопросов, удалите одно или измените определение. –

Смежные вопросы