为什么我的quizzcount的价值翻了一番

时间:2013-12-12 22:40:13

标签: java

我遇到这个代码的问题,因为quizzcount变量没有输出正确的值,它使值加倍。

我通过将quizzcount潜水2来找到了解决方法并且它有效,但我真的想弄明白为什么它的价值加倍。

因此,例如,如果不将quizzcount除以2,如果用户在10个问题中得到7个正确,则messagedialog将显示用户得到14个中的14个正确。

造成这种情况的原因是什么?

谢谢你们,任何帮助都将不胜感激。

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidClassException;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.*;
import java.util.*;

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

public class MathFiles extends JFrame implements ActionListener
{
private ObjectOutputStream toFile;
private String name;
private boolean open;
private static String response;
private static int menuOption = 0;
private static int numberOfMaths = 0;
private FileInputStream fis;
private ObjectInputStream fromFile;
Math aMath = null;
private int quizcount =0;
String checkbutton = "";
private static int tracker =1;
int count = 0;
int fimage =0;


JRadioButton questA, questB, questC, questD, questE;
ButtonGroup  questGroup;
JPanel       questPanel;

JLabel       question;
JPanel       questionPanel;

JTextField   resultText;
JLabel       resultLabl;
JPanel       resultPanel;

JButton      nextButton;
JPanel       quizPanel;

ImageIcon    image;
JLabel       imageLabl;
JPanel       imagePanel;

JTextArea    questionText;
JScrollPane  scrollPane;

Random       rand;



/** @param fileName is the desired name for the binary file. */
public MathFiles()
{
    setTitle( "Math Quiz Competition" );

    rand = new Random();
    toFile = null;
    //tracker =  rand.nextInt(5)+1;
    tracker = 1;


    name = "Quiz"+tracker+".txt";
    open = false;

    //openFile(); //Use only when creating file
    //writeMathsToTextFile(name);
    setLayout( new FlowLayout() ); 
    inputFile();
    beginquiz();
    showquestions();
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   

} // end MathFiles constructor


/** Writes all Maths from a text file and writes them to a binary file.
    @param fileName the text file */
public void writeMathsToTextFile(String fileName)
{
    Scanner inputFile = null;
    Math nextMath = null;
    String question_num;
    String question;
    String answera;
    String answerb;
    String answerc;
    String answerd;
    String answer_cor;
    String file_name;
    String SENTINEL ="DONE";


    try
    {
        inputFile = new Scanner(new File(fileName));
    }
    catch(FileNotFoundException e)
    {
        System.out.println("Text file " + fileName + " not found.");
        System.exit(0);
    }

    Scanner keyboard = new Scanner(System.in);

    System.out.print("Question number: ");
    question_num = keyboard.nextLine();
    while (!question_num.equalsIgnoreCase(SENTINEL))
    {

     System.out.print("Question: ");
     question = keyboard.nextLine();

     System.out.print("Answer A: ");
     answera = keyboard.nextLine();

     System.out.print("Answer B: ");
     answerb = keyboard.nextLine();

     System.out.print("Answer C: ");
     answerc = keyboard.nextLine();

     System.out.print("Answer D: ");
     answerd = keyboard.nextLine();

     fimage = rand.nextInt(30)+1;
     file_name = "image"+fimage+".gif";
     System.out.print(file_name);

     System.out.print("Correct Answer: ");
     answer_cor = keyboard.nextLine();



     nextMath = new Math(question_num, question, answera, answerb, 
                answerc, answerd, answer_cor, file_name);
     writeAnObject(nextMath);
     numberOfMaths++;

     System.out.print("\nQuestion number: ");
     question_num = keyboard.nextLine();
    } // end while


    System.out.println("successfully created = " + name);
} // end readMathsFromTextFile




/** Opens the binary file for output. */
public void openFile()
{
    try
    {
        FileOutputStream fos = new FileOutputStream(name);
        toFile = new ObjectOutputStream(fos);
        open = true;
    }
    catch (FileNotFoundException e)
    {
        System.out.println("Cannot find, create, or open the file " + name);
        System.out.println(e.getMessage());
        open = false;
    }
    catch (IOException e)
    {
        System.out.println("Error opening the file " + name);
        System.out.println(e.getMessage());
        open = false;
    }
    //System.out.println("successfully opened = " + name);
} // end openFile



/** Writes the given object to the binary file. */
public void writeAnObject(Serializable anObject)
{
    try
    {
        if (open)
            toFile.writeObject(anObject);
    }
    catch (InvalidClassException e)
    {
        System.out.println("Serialization problem in writeAnObject.");
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch (IOException e)

    {
        System.out.println("Error writing the file " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
} // end writeAnObject

public void result()
{
    System.out.println("Your score is");

}



public void inputFile()
{

    try
    {
        fromFile = new ObjectInputStream(new FileInputStream(name));

    }

    catch(StreamCorruptedException e)
    {
        System.out.println("Error in input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(IOException e)
    {
        System.out.println("Error reading input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
} // end displayFile




/** Closes the binary file. */
public void closeFile()
{
    System.out.println("closed name = " + name);
    try
    {
        toFile.close();
        open = false;
    }
    catch (IOException e)
    {
        System.out.println("Error closing the file " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
} // end closeFile

/** @return the fileís name as a string */
public String getName()
{
    return name;
} // end getName

/** @return true if the file is open */
public boolean isOpen()
{
    return open;
} // end isOpen

public void beginquiz()
{

    try
    {
        aMath = (Math)fromFile.readObject();
    }
    catch (ClassNotFoundException e)
    {
        System.out.println("The class Math is not found.");
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(StreamCorruptedException e)
    {
        System.out.println("Error in input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(IOException e)
    {
        System.out.println("Error reading input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }  

}

void showquestions()
{

    //question group
    /*question  = new JLabel();
    question.setText(aMath.getquestion());
    question.setFont(new Font("Arial", Font.BOLD, 20));
    question.setForeground(Color.BLUE);
    questionPanel = new JPanel();
    questionPanel.add( question );*/

    questionText  = new JTextArea(5,20);
    questionText.setWrapStyleWord(true);
    questionText.setLineWrap(true);
    questionText.setText(aMath.getquestion());
    questionText.setFont(new Font("Arial", Font.BOLD, 20));
    questionText.setForeground(Color.BLUE);
    questionPanel = new JPanel();
    questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.PAGE_AXIS));
    questionPanel.add( questionText );


    // quest group
    questA = new JRadioButton(aMath.getanswera(), false );
    questB = new JRadioButton(aMath.getanswerb(), false );
    questC = new JRadioButton(aMath.getanswerc(), false );
    questD = new JRadioButton(aMath.getanswerd(), false );


    questGroup = new ButtonGroup();
    questGroup.add( questA ); 
    questGroup.add( questB );
    questGroup.add( questC ); 
    questGroup.add( questD );


    questPanel = new JPanel();
    questPanel.setLayout( new BoxLayout( questPanel, BoxLayout.Y_AXIS ) );
    questPanel.add( new JLabel("Choose the Correct Answer") );
    questPanel.add( questA ); 
    questPanel.add( questB );
    questPanel.add( questC ); 
    questPanel.add( questD );



    // result panel
    //resultText  = new JTextField(20);
    //resultText.setEditable( false );   
    //resultLabl  = new JLabel("Result");
    //resultPanel = new JPanel();
    //resultPanel.add( resultLabl );
    //resultPanel.add( resultText );


    //button
    nextButton = new JButton("Next");
    quizPanel = new JPanel();
    quizPanel.add(nextButton);


   //Image image1 = new ImageIcon("image/image1.gif").getImage();
    image = new ImageIcon("image1.gif");
    imageLabl=new JLabel(image);
    imagePanel = new JPanel();
    imagePanel.add(imageLabl);

    // frame:  use default layout manager
    add( imagePanel);
    add( questionPanel);
    add( questPanel);
    //add( resultPanel);

    questA.setActionCommand(aMath.getanswera());
    questB.setActionCommand(aMath.getanswerb());
    questC.setActionCommand(aMath.getanswerc());
    questD.setActionCommand(aMath.getanswerd());

    questA.addActionListener(this);
    questB.addActionListener(this);
    questC.addActionListener(this);
    questD.addActionListener(this);


    nextButton.setActionCommand( "next" );   // set the  command 

    // register the buttonDemo frame
    // as the listener for both Buttons.
    nextButton.addActionListener( this );
    add(quizPanel);

}

public void actionPerformed( ActionEvent evt)
{
  //evt.getActionCommand() = aMath.getanswer_cor();


if (questA.isSelected()&& 
    aMath.getanswera().equalsIgnoreCase(aMath.getanswer_cor().trim()))
    quizcount++;

if (questB.isSelected()&& 
    aMath.getanswerb().equalsIgnoreCase(aMath.getanswer_cor().trim()))
    quizcount++; 

if (questC.isSelected()&& 
    aMath.getanswerc().equalsIgnoreCase(aMath.getanswer_cor().trim()))  
    quizcount++; 

if (questD.isSelected()&& 
   aMath.getanswerd().equalsIgnoreCase(aMath.getanswer_cor().trim()))
   quizcount++;


if(questA.isSelected() || questB.isSelected() || questC.isSelected() || questD.isSelected())


 if ( evt.getActionCommand().equals( "next" ))
{

   try
    {
        aMath = (Math)fromFile.readObject();      
        questionText.setText(aMath.getquestion());
        questA.setText(aMath.getanswera());
        questB.setText(aMath.getanswerb());
        questC.setText(aMath.getanswerc());
        questD.setText(aMath.getanswerd());
        imageLabl.setIcon(new ImageIcon(aMath.getfile()));

        questGroup.clearSelection();  

        repaint();

    }
    catch (ClassNotFoundException e)
    {
        System.out.println("The class Math is not found.");
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(StreamCorruptedException e)
    {
        System.out.println("Error in input stream: " + name);
        System.out.println(e.getMessage());
        System.exit(0);
    }
    catch(IOException e)
    {
        if (count<=0)
           count = 0;
        else 
           count--;
        JOptionPane.showMessageDialog(null,"Your score is "+quizcount/2 +" out of 10");
        try{
          Thread.sleep(2000);
          System.exit(0);
        }catch (InterruptedException em) { }
    }  




}



}



public static void main ( String[] args )
{
    MathFiles mat = new MathFiles();
    mat.setSize( 450, 550 );  
    mat.setLocationRelativeTo(null);
    mat.setResizable( false ); 
    mat.setVisible( true ); 
}

} // end MathFiles


class Math implements java.io.Serializable
{
private String question_num;
private String question;
private String answera;
private String answerb;
private String answerc;
private String answerd;
private String answer_cor;
private String file_name;




public Math(String quesno, String quest, String ansa, String ansb, String ansc, 
         String ansd, String ans_cor, String file) 
{

   question_num = quesno;
   question = quest;
   answera = ansa; 
   answerb = ansb; 
   answerc = ansc; 
   answerd = ansd; 
   answer_cor = ans_cor; 
   file_name = file;
}           



public void setquestion(String lName)
{
    question = lName;
} // end setquestion


public void setquestion_num(String fName)
{
    question_num = fName;
} // end setquestion_num

public void setanswera(String add)
{
    answera = add;
} // end setanswera


public void setanswerb(String cty)
{
    answerb = cty;
} // end setanswerb


public void setanswerc(String st)
{
    answerc = st;
} // end setanswerc


public void setanswerd(String z)
{
    answerd = z;
} // end setanswerd


public void setanswer_cor(String phn)
{
    answer_cor = phn;
} // end setanswer_corr


public String getquestion_num()
{
    return question_num;
} // end getquestion_num

/** @return the question */
public String getquestion()
{
    return question;
} // end getquestion

/** @return the answera*/
public String getanswera()
{
    return answera;
} // end getanswera

/** @return the answerb */
public String getanswerb()
{
    return answerb;
} // end getanswerb


public String getanswerc()
{
    return answerc;
} // end getanswerc


public String getanswerd()
{
    return answerd;
} // end getanswerd


public String getanswer_cor()
{
    return answer_cor;
} // end getanswer_corr

public String getfile()
{
    return file_name;
} // end getanswer_corr




/** @return the Math information */
public String toString()
{
    String myMath = getquestion_num() + " " + getquestion() + "\n";
    myMath += getanswera() + "\n";
    myMath += getanswerb() + " " + getanswerc() + " " + getanswerd() + "\n";
    myMath += getanswer_cor() + "\n";
    myMath += getfile() + "\n";

    return myMath;
} // end toString

} // end Math

1 个答案:

答案 0 :(得分:0)

看起来您的问题是您已在单选按钮上注册了ActionListeners。这意味着当您选择答案并单击“下一步”按钮时会触发事件。考虑到这一点,显而易见的是,为什么你的分数会翻倍。

据我所知,单选按钮不需要ActionListeners。您应该只在用户表明已完成选择时检查答案。分数正好加倍,这也表明除了天真地选择一个单选按钮并点击“下一步”之外,你基本上没有测试过程序。在注释掉将侦听器添加到单选按钮的行之前,请尝试更改答案。打开程序,选择正确答案,然后选择错误答案,然后再次选择正确答案并单击“下一步”。看看会发生什么。

使用调试器也可以轻松找到此类错误。只需在actionPerformed中插入一个断点,很明显它会被多个动作调用。