有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing尝试使用Netbeans问答游戏在Java中制作下一个按钮

我做了一个问答游戏,我对“下一步”按钮有问题。“下一步”按钮必须转到下一个问题和下一个答案。第一次执行“下一步”按钮后,将转到第一个问题和答案,但不会继续到第二个问题和答案

guiandtests3。JAVA 包guiandtests3

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Guiandtests3 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException, ParseException {
       gui3 form = new gui3();
       form.setVisible(true);

       Random random = new Random();
        int a = random.nextInt(3+1-0)+0;
        int b = random.nextInt(3+1-0)+0;
        int c = random.nextInt(3+1-0)+0;
        int d = random.nextInt(3+1-0)+0;


       JSONParser parser = new JSONParser();
       Object obj = null;
       obj = parser.parse(new FileReader("c:\\Matematika.json"));
       JSONObject jsonObject = (JSONObject) obj;
       JSONArray array = (JSONArray) jsonObject.get("data");

       Iterator<Object> iterator = array.iterator();
       //form.s11();
       while (iterator.hasNext() ) {
              //System.out.println("a");
              if (form.getter()==form.g11()){
                  //System.out.println("abc");
                JSONObject element=(JSONObject)iterator.next();
                JSONArray abc = (JSONArray) element.get("jawaban");
                Iterator<Object> iterator1 = abc.iterator();
                ArrayList<String> results = new ArrayList<>();

                System.out.println(element.get("soal"));

                form.setquestion((String) element.get("soal"));


               while (iterator1.hasNext()) {

                           results.add(iterator1.next().toString());
                           //System.out.println(iterator1.next());
                        }


               System.out.println(results.get(0));
                       System.out.println(results.get(1));

               while(a==b){
                           b = random.nextInt(3+1-0)+0;
                       }
                       while(a==c | b ==c){
                           c = random.nextInt(3+1-0)+0;
                       }
                       while(a==d | b ==d |c==d){
                           d = random.nextInt(3+1-0)+0;
                       }
                       form.setAnswer1(results.get(a));
                       form.setAnswer2(results.get(b));
                       form.setAnswer3(results.get(c));
                       form.setAnswer4(results.get(d));

                       form.setanswer(results.get(0));
                form.s11();
              }

    }

    }

}

桂3。爪哇

package guiandtests3;
import javax.swing.JOptionPane;
/**
 *
 * @author abc
 */
public class gui3 extends javax.swing.JFrame {

    public  String question;
    public  String answer1;
    public  String answer2;
    public  String answer3;
    public  String answer4;

    private int i=0;
    private int aa=0;
    private String correctanswer="empty";

    public gui3() {
        initComponents();
    }

    public void setanswer(String answer){
        correctanswer = answer;
    }

    public String getanswer(){
        return correctanswer;
    }

    public void setter(){
        this.i = this.i +1;
    }

    public int getter(){
        return this.i;
    }

    public void s11(){
        this.aa=this.aa+1;
    }
    public int g11(){
        return this.aa;
    }

    public void setAnswer1(String answer){
        this.answer1=answer;
    }

    public String getAnswer1(){
        return this.answer1;
    }

    public void setAnswer2(String answer){
        this.answer2= answer;
    }

    public String getAsnwer2(){
        return this.answer2;
    }

    public void setAnswer3(String answer){
        this.answer3= answer;
    }

    public String getAsnwer3(){
        return this.answer3;
    }

    public void setAnswer4(String answer){
        this.answer4= answer;
    }

    public String getAsnwer4(){
        return this.answer4;
    }

    public void setquestion(String question){
        this.question=question;
    }

    public String getquestion(){
        return this.question;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("jLabel1");

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("jButton2");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("jButton3");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("jButton4");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("Next");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(176, 176, 176)
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(156, 156, 156)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton2)
                                    .addComponent(jButton1)
                                    .addComponent(jButton3)
                                    .addComponent(jButton4))))
                        .addGap(0, 161, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton5)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(47, 47, 47)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addGap(18, 18, 18)
                .addComponent(jButton3)
                .addGap(18, 18, 18)
                .addComponent(jButton4)
                .addGap(18, 18, 18)
                .addComponent(jButton5)
                .addContainerGap(34, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        JOptionPane.showMessageDialog(rootPane,getanswer(),null,JOptionPane.ERROR_MESSAGE);
        if(jButton1.getText() == getanswer() ){
            JOptionPane.showMessageDialog(rootPane,"Correct",null,JOptionPane.ERROR_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(rootPane,"Wrong",null,JOptionPane.ERROR_MESSAGE);
        }
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if(jButton2.getText() == getanswer() ){
            JOptionPane.showMessageDialog(rootPane,"Correct",null,JOptionPane.ERROR_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(rootPane,"Wrong",null,JOptionPane.ERROR_MESSAGE);
        }
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if(jButton3.getText() == getanswer() ){
            JOptionPane.showMessageDialog(rootPane,"Correct",null,JOptionPane.ERROR_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(rootPane,"Wrong",null,JOptionPane.ERROR_MESSAGE);
        }
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if(jButton4.getText() == getanswer() ){
            JOptionPane.showMessageDialog(rootPane,"Correct",null,JOptionPane.ERROR_MESSAGE);
        }else{
            JOptionPane.showMessageDialog(rootPane,"Wrong",null,JOptionPane.ERROR_MESSAGE);
        }
    }                                        

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jLabel1.setText(question);
        jButton1.setText(answer1);
        jButton2.setText(answer2);
        jButton3.setText(answer3);
        jButton4.setText(answer4);
        setter();
    }                                        

    /**
     * @param args the command line arguments
     */
    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(gui3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(gui3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(gui3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(gui3.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 gui3().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

json文件

{
"data":[
{
    "id":"1",
    "soal":"3 * 3 + 2 =",
    "jawaban":[
        "11",
        "15",
        "17",
        "19"
    ]

},
{
    "id":"2",
    "soal":"20 / 5 =",
    "jawaban":[
        "4",
        "3",
        "2",
        "1"
    ]
},
{
    "id":"3",
    "soal":"16 + 6 = ",
    "jawaban":[
        "22",
        "21",
        "20",
        "24"
    ]
},
{
    "id":"4",
    "soal":"2 * 4 =",
    "jawaban":[
        "8",
        "6",
        "10",
        "12"
    ]
},
{
    "id":"5",
    "soal":"1+4*2",
    "jawaban":[
        "8",
        "10",
        "12",
        "14"
    ]
},
{
    "id":"6",
    "soal":"Jika A+1=10 , B+A=11 C= ?",
    "jawaban":[
        "EGP",
        "1",
        "12",
        "22"
    ]
},
{
    "id":"7",
    "soal":"44/11",
    "jawaban":[
        "4",
        "2",
        "5",
        "8"
    ]
},
{
    "id":"8",
    "soal":"1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 = ",
    "jawaban":[
        "16",
        "15",
        "17",
        "10"
    ]
},
{
    "id":"9",
    "soal":"Berapakah jawaban sebelumnya ",
    "jawaban":[
        "16",
        "17",
        "18",
        "19"
    ]
}
]
}

press to see the GUI


共 (1) 个答案

  1. # 1 楼答案

    您需要将问题和答案传递到gui对象中,以便迭代器可以实际移动到下一个“结果”

    您应该在“下一步”按钮中移动到下一个结果,而不是从主功能,因为您的gui无法访问这些问题,并且gui中的任何内容都无法从您在主功能中从数据文件收集的结果中获取信息

    考虑将文件的初始读取从main函数移到“Gui3”对象构造函数,并将“结果”数组列表作为GUI的实例变量可用。

    JSON文件的第一次读取与您使用的随机数非常混淆,但您需要找出一种方法,将问题与答案排列在一个数组中

    例如:

    ArrayList<ArrayList<String>>  results = new ArrayList<ArrayList<String>>();
    ArrayList<String> question = new ArrayList<>()
    question.add(question);
    question.add(answer1);
    question.add(answer2);
    question.add(answer3);
    question.add(answer4);
    results.add(questions);
    

    然后当你按下“下一步”按钮时,你可以

    jLabel1.setText(results.get(i).get(0));
    jButton1.setText(results.get(i).get(1));
    jButton2.setText(results.get(i).get(2));
    jButton3.setText(results.get(i).get(3));
    jButton4.setText(results.get(i).get(4));
    i++;  // Or use your setter() function?
    

    根据评论中关于如何将JSON放入数组列表的问题,这与您现在的做法非常相似,但您需要将其“添加”到ArrayList中,而不是立即使用它

    比如:

    JSONParser parser = new JSONParser();
    Object obj = null;
    obj = parser.parse(new FileReader("c:\\Matematika.json"));
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray array = (JSONArray) jsonObject.get("data");
    ArrayList<ArrayList<String>>  results = new ArrayList<ArrayList<String>>();
    ArrayList<String> question = new ArrayList<>();
    
    Iterator<Object> iterator = array.iterator();
    while (iterator.hasNext() ) {
        String questionString = element.get("soal");
        question.add(questionString);
        JSONArray answers = (JSONArray) jsonObject.get("jawaban");
        Iterator<String> iterator2 = answers.iterator();
        int count = 0;
        //The following limits it to pulling back 4 answers from the JSON jawaban element
        while (iterator2.hasNext() && count < 4) {
            String answer = iterator2.next();
            question.add(answer);
            count++;
        }
        results.add(question);
    }
    

    将此代码放入GUI 3对象的构造函数中,或者将其传递到GUI 3构造函数中,并使构造函数的结果如下所示:

    public class gui3 extends javax.swing.JFrame {
        ArrayList<ArrayList<String>> results;
    
        //Your other code here
    
        public gui3(ArrayList<ArrayList<String>> results) {
            this.results = results;
            initComponents();
        }
    
        // Your other code here
    }
    

    请注意,您需要将这个results ArrayList放在类实例范围内,因此需要将声明移到构造函数之外