设计一份考试程序,包含四道单选题和四道多选题,单选题答对一道得1分,多选答对一道得1.5分, 
要求学生能在程序的指导下做题,一直得到最终的分数。 
要求用JAVA实现。运用面向对象的方式,至少包含试卷,问题,答案三个类。 import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.awt.geom.*; 
import java.awt.font.*; 
import java.util.*; 
import java.io.*; 
public class Exam { 
    public static void main(String[] args) { 
        JFrame f = new ExamFrame(); 
        f.setVisible(true); 
    } 

class ExamFrame extends JFrame { 
    static int singlequestion; 
    static int singleanswer; 
    static int multiplyquestion; 
    static int multiplyanswer; 
    static { 
        Properties prop = new Properties(); 
        try { 
            prop.load(new FileInputStream("exam.properties")); 
        } catch (FileNotFoundException ex) { 
            ex.printStackTrace(); 
        } catch (IOException ex) { 
            ex.printStackTrace(); 
        } 
        singlequestion = Integer.parseInt(prop.getProperty("singlequestion")); 
        singleanswer = Integer.parseInt(prop.getProperty("singleanswer")); 
        multiplyanswer = Integer.parseInt(prop.getProperty("multiplyanswer")); 
        multiplyquestion = Integer.parseInt(prop.getProperty("multiplyquestion")); 
    } 
    Question[] qs = new Question[singlequestion]; 
    Question2[] q2s = new Question2[multiplyquestion]; 
    Score score = new Score(); 
    int rightcount; 
    JLabel scoreLabel = new JLabel(); 
    public ExamFrame() { 
        setSize(600,700); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setLayout(new GridLayout(12,1)); 
        JPanel titlePanel = new TitlePanel(); 
        add(titlePanel); 
        Scanner scan = null; 
        try { 
            scan = new Scanner(new File("exam.txt")); 
        } catch (FileNotFoundException ex) { 
            ex.printStackTrace(); 
        } 
        int index=0; 
        while(scan.hasNextLine()&&index <singlequestion) { 
            String temp = scan.nextLine();  //System.out.println(temp); 
            String[] temps = temp.split("!"); 
            Answer[] answers = new Answer[singleanswer]; 
            ButtonGroup group = new ButtonGroup(); 
            for(int i = 1;i <5;i++) { 
                answers[i-1] = new Answer(temps[i]); 
                group.add(answers[i-1]); 
            } 
           qs[index] = new Question(temps[0],score,answers); 
           qs[index].setRightAnswer(Integer.parseInt(temps[5])); 
            add(qs[index++]); 
             
        } 
        index = 0; 
        while(scan.hasNextLine()) { 
            String temp = scan.nextLine(); 
            String[] temps = temp.split("!"); 
            Answer2[] answer2s = new Answer2[multiplyanswer]; 
            for(int i=1;i <7;i++) { 
                answer2s[i-1] = new Answer2(temps[i]); 
            } 
            q2s[index] = new Question2(temps[0],score,answer2s); 
            int answersize = temps.length - 7; 
            int[] rightanswers = new int[answersize]; 
            int index2 = 0; 
            for(int i = 7;i <temps.length;i++) { 
                rightanswers[index2++] = Integer.parseInt(temps[i]); 
            } 
            q2s[index].setRightAnswers(rightanswers); 
            add(q2s[index++]); 
        } 
        JPanel buttonPanel = new JPanel(); 
        JButton submit = new JButton("Submit"); 
        add(buttonPanel); 
        buttonPanel.add(submit); 
        submit.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent e) { 
                EventQueue.invokeLater(new Runnable() { 
                    public void run() { 
                   for(Question temp:qs) { 
                        if(temp.check()) { 
                        rightcount+=1; 
                        temp.score();                    
                       } 
                   } 
                   for(Question2 temp2:q2s) { 
                       if(temp2.check()) { 
                        rightcount+=1; 
                        temp2.score();                    
                       } 
                   } 
                    scoreLabel.setText("you gave "+rightcount+" right answer,\r\n you got "+score.getResult()+" point"); 
                    add(scoreLabel); 
                    rightcount = 0; 
                    validate(); 
            }  
                }); 
            }   
        }); 
    } 

解决方案 »

  1.   

    class Answer extends JRadioButton{ 
        public Answer(String text) { 
            setText(text); 
        } } 
    class Answer2 extends JCheckBox { 
       //String text; 
        public Answer2(String text) { 
            setText(text); 
        } 

    class Question extends JPanel { 
        String text; 
        Score score; 
        Answer[] answers; 
        int flag ; 
        boolean inited; 
        public Question(String text,Score s,Answer[] as) { 
            this.text = text; 
            score = s; 
            answers = as; 
            setLayout(new GridLayout(2,1)); 
            JLabel l = new JLabel(text); 
            add(l); 
            JPanel p = new JPanel(); 
            add(p); 
            p.setLayout(new GridLayout(1,4)); 
            for(int i = 0;i <answers.length;i++)  
                p.add(answers[i]); 
        } 
        public void setRightAnswer(int i) { 
            inited = true; 
            flag = i; 
        }     public boolean check() { 
            if(inited&&answers[flag].isSelected()) 
                return true; 
            return false; 
        } 
        public void score() { 
                score.add(1); 
        } 

    class Question2 extends JPanel { 
        //String text; 
        Answer2[] answers; 
        Score score; 
        int[] rightanswers; 
        int flag; 
        public Question2(String text,Score s,Answer2[] sa) { 
           // this.text = text; 
            score = s; 
            answers = sa; 
            setLayout(new GridLayout(2,1)); 
            JLabel l = new JLabel(text); 
            add(l); 
            int size = answers.length; 
            JPanel buttonPanel = new JPanel(); 
            add(buttonPanel); 
            buttonPanel.setLayout(new GridLayout(1,size)); 
            for(int i=0;i <size;i++) 
                buttonPanel.add(answers[i]); 
        } 
        public void setRightAnswers(int[] f) { 
            rightanswers = f; 
            flag = f.length; 
        } 
        public void score() { 
            if(check()) 
                score.add(1.5); 
        } 
        public boolean check(){ 
            for(int index:rightanswers) { 
                if(!answers[index].isSelected())  
                    return false; 
            } 
            for(int i=0;i <answers.length;i++)  
                if(answers[i].isSelected()&&!insideAset(i,rightanswers))  
                    return false; 
            return true; 
        } 
            public static boolean insideAset(int i,int[] arr) { 
                for(int temp:arr) { 
                    if(temp==i) 
                        return true; 
                } 
                return false; 
            } 
    } class Score { 
        double score ; 
        public void add(double d) { 
            score += d; 
        } 
        public double get() { 
            return score; 
        } 
        public double getResult() { 
            double result = score; 
            score = 0; 
            return result; 
        } 

    class TitlePanel extends JPanel { 
        static String text ; // = "Exam Test:for the java programmer"; 
        static { 
           Properties prop = new Properties(); 
            try { 
                prop.load(new FileInputStream("exam.properties")); 
            } catch (FileNotFoundException ex) { 
                ex.printStackTrace(); 
            } catch (IOException ex) { 
                ex.printStackTrace(); 
            } 
           text = prop.getProperty("title"); 
        } 
        public TitlePanel() {} 
        public TitlePanel(String text) { 
            text = text; 
        } 
        public void paintComponent(Graphics g) { 
            super.paintComponent(g); 
            if(text==null) { 
                System.out.println("paint:text == null!"); 
                return; 
            } 
            Graphics2D g2 = (Graphics2D)g; 
            Font titleFont = new Font("SansSerif", Font.BOLD, 20); 
            FontRenderContext context = g2.getFontRenderContext(); 
            Rectangle2D rect = titleFont.getStringBounds(text,context); 
            float X = (float)(getWidth()-rect.getWidth())/2; 
            float Y = -(float)(rect.getY()); 
            System.out.println(X+" "+Y); 
            g2.setFont(titleFont); 
            g2.drawString(text,X,Y); 
        } 
    } 这是我当时的解决方案,用下面几个类来实现:Exam,ExamFrame,Score,Question,Answer,Question2,Answer2,这几个主要的类再加上一个试卷标题类TitlePanel。 
    Question和Question2分别表示单选题和多选题,Answer和Answer2分别表示单选答案和多选答案。由于单选答案我想用单选框按钮实现,而多选答案我想用复选框来实现, 
    所以我没有让他们继承同一个类,这样代码显得有点冗余。我想把Question和Question2整合进一个基类中,把Answer和Answer也整合进一个基类中,
      

  2.   

    楼主的程序重复代码比较多。我觉得用写成命令行程序更好,逻辑更清晰,我随便写了一下,供你参考:
    // Test.javaimport java.util.*;public class Test {

    private ArrayList<Question> questions = new ArrayList<Question>();
    private ArrayList<int[]> selectedChoices = new ArrayList<int[]>();
    private int curIndex = -1;
    private float score;
    Scanner scanner = new Scanner(System.in);

    public void addQuestion(Question q) {
    questions.add(q);
    selectedChoices.add(null);
    }

    public void start() {
    System.out.println("Start of test.\n");
    nextQuestion();
    }

    private void prevQuestion() {
    if (curIndex <= 0) {
    System.out.println("This is already the first question. Skip(K), Finish(F)?");
    if (!jump(scanner.nextLine().trim())) prevQuestion();
    }
    else {
    System.out.println(questions.get(--curIndex));
    promt();
    }
    } private void nextQuestion() {
    if (curIndex >= questions.size() - 1) {
    System.out.println("This is already the last question. Back(B), Finish(F)?");
    if (!jump(scanner.nextLine().trim())) nextQuestion();
    }
    else {
    System.out.println(questions.get(++curIndex));
    promt();
    }
    }

    private void promt() {
    System.out.println("Give your choice below or Skip(K), Back(B), Finish(F):");
    System.out.println("Use a comma or a space to separate multiple choices.");
    String line = scanner.nextLine().trim();
    if (!jump(line)) {
    String[] choice = line.split("[ \\,]+");
    int[] validChoice = new int[choice.length];
    for (int i = 0; i < choice.length; i++) {
    try {
    validChoice[i] = Integer.parseInt(choice[i]);
    if (validChoice[i] < 1 || validChoice[i] > questions.get(curIndex).getAnswerCount())
    throw new NumberFormatException();
    } catch(NumberFormatException e) {
    kidding();
    promt();
    }
    }
    confirm(validChoice);
    }
    }

    private void confirm(int[] choice) {
    System.out.print("Your choice is: ");
    for (int i = 0; i < choice.length; i++) {
    if (i > 0) System.out.print(", ");
    System.out.print(choice[i]);
    }
    System.out.println("\nYes(Y), No(N), Skip(K), Back(B), Finish(F)?");
    String line = scanner.nextLine().trim();
    if (!jump(line)) {
    if (line.equalsIgnoreCase("y") || line.equalsIgnoreCase("yes")) {
    selectedChoices.set(curIndex, choice);
    System.out.println();
    nextQuestion();
    }
    else {
    if (!line.equalsIgnoreCase("n") && !line.equalsIgnoreCase("no"))
    kidding();
    promt();
    }
    }
    }

    private void kidding() {
    System.out.println("Are you kidding?");
    }

    private boolean jump(String line) {
    if (line.equalsIgnoreCase("k") || line.equalsIgnoreCase("skip")) {
    System.out.println();
    nextQuestion();
    return true;
    }
    else if (line.equalsIgnoreCase("b") || line.equalsIgnoreCase("back")) {
    System.out.println();
    prevQuestion();
    return true;
    }
    else if (line.equalsIgnoreCase("f") || line.equalsIgnoreCase("finish")) {
    System.out.println();
    stop();
    return true;
    }
    else return false;
    }

    private void stop() {
    Iterator<Question> itq = questions.iterator();
    Iterator<int[]> itc = selectedChoices.iterator();
    int correctChoices = 0;
    while(itq.hasNext() && itc.hasNext()) {
    Question q = itq.next();
    int[] c = itc.next();
    if (q.isCorrectChoice(c)) {
    score += (q.getStyle() == Question.ChoiceStyle.SINGLE_CHOICE ? 1 : 1.5F);
    correctChoices++;
    }
    }
    System.out.println("End of test.");
    System.out.println("You got a score of " + score);
    System.out.println(correctChoices + " of " + selectedChoices.size() + " choices are correct.");
    System.out.println("Thank you for testing, bye!");
    }

    public static void main(String[] args) {
    Test test = new Test();
    test.addQuestion(
    new Question("Which one of the following cities is the capital city of China?",
    new String[] { "Beijing", "Shanghai", "Tianjin", "Xi'an" },
    1,
    Question.ChoiceStyle.SINGLE_CHOICE
    ));
    test.addQuestion(
    new Question("Which of the following musical instruments are string instruments?",
    new String[] { "Piano", "Violin", "Cello", "Flute" },
    new int[] { 2, 3 },
    Question.ChoiceStyle.MULTI_CHOICE
    ));
    test.start();
    }}// Question.javaimport java.util.Arrays;public class Question {

    public static enum ChoiceStyle { SINGLE_CHOICE, MULTI_CHOICE }; private String question;
    private String[] answers;
    private int[] key;
    private ChoiceStyle style;

    /*
     * constructor for single-choice question
     */
    public Question(String q, String[] a, int k, ChoiceStyle choiceStyle) {
    question = q;
    answers = a;
    key = new int[] { k };
    style = choiceStyle;
    }

    /*
     * constructor for multi-choice question
     */
    public Question(String q, String[] a, int[] k, ChoiceStyle choiceStyle) {
    question = q;
    answers = a;
    key = k;
    style = choiceStyle;
    if (k != null) Arrays.sort(key);
    }

    public String toString() {
    StringBuffer buf = new StringBuffer();
    buf.append(question);
    buf.append(' ');
    buf.append(style == ChoiceStyle.SINGLE_CHOICE ? "[Single-Choice]" : "[Multiple_Choice]");
    buf.append('\n');
    for (int i = 0; i < answers.length; i++) {
    buf.append(i+1);
    buf.append(". ");
    buf.append(answers[i]);
    buf.append('\n');
    }
    return buf.toString();
    }

    public boolean isCorrectChoice(int[] choice) {
    if (choice == null) return false;
    Arrays.sort(choice);
    return Arrays.equals(choice, key);
    }

    public ChoiceStyle getStyle() {
    return style;
    }

    public int getAnswerCount() {
    return answers.length;
    }}
      

  3.   

    exam.txt
    1,你叫什么名字?!A,周**!B,彭**!C,彭*!D,毛*!2
    2,你最喜欢的宠物是什么?!A,狗!B,小猫!C,老鼠!D,鸟!2
    3,when you first come to Changsha,what's your feeling?!A,exciting!B,Incredible!C,Ironic!D,sad!2
    4,What's you job?!A,java developer!B,C developer!C,pb developer!D,System designer!2
    5,你的兴趣和爱好有哪些?!A,游泳!B,篮球!C,吉他!D,钢琴!E,软件开发!F,软件设计!0!1!2!3!4!5
    6,你用过下面的哪些名字?在你上学的时候。!A,周*!B,彭**!C,彭*!D,毛*!E彭**!F深灰色MAN!0!1!2
    7,There list some programming language,are you realy love?!A,java!B,PB!C,Sql Server!D,Oracle!E,Mysql!F,C++!0!2!3!4!5
    8,There are some Country in here,which Country did you want travelling?!A,USA!B,British!C,Japan!D,French!E,Germeny!F,Italy!0!1!2!3!4!5!6
      

  4.   

    exam.propertiestitle = Exam Test:for the java programmer
    singlequestion = 4
    singleanswer = 4
    multiplyquestion = 4
    multiplyanswer = 6
      

  5.   

    以上的两个文件也是一部分!
    这是大概的运行界面:
      [/img]
      

  6.   

    程序是运行过的,
    程序的参数都可以在
    exam.properties 这个文件中指定
    title = Exam Test:for the java programmer //考试标题
    singlequestion = 4 //单选题的数量
    singleanswer = 4   //单选题的可选答案数
    multiplyquestion = 4  //多选题的数量
    multiplyanswer = 6    //多选题的可选答案数在exam.properties里完成参数的指定后,
    再修改exam.txt 这个文件,这个文件是用来设计试卷内容的.
      

  7.   

    你说给我个.net开发工具,画几个单选框和多选框完事,用java做这个要人命啊
      

  8.   

    青果待遇怎么样?LZXD 介绍下
      

  9.   

    swing  一年不用了  基本忘完了
      

  10.   

    你们说当遇到这种题时是不是用j2se(命令行、swing)或 j2ee写都行啊?
      

  11.   

    是的,也可以用J2EE解决.
    用JSP+SERVLET+JAVABEAN就OK了!