Почему моя Java-программа открывает два экземпляра / окна? - PullRequest
0 голосов
/ 12 марта 2019

Я пытаюсь сделать простую игру / проект БлэкДжек для школы.Пока что я запускаю его - все идет хорошо, но вместо одного открывается только два окна / окна JFrame.Вот код для игрового цикла, который находится в классе под названием (BlackJackProject).Ниже этого кода я также поместил код для формы / файла JFrame, который открывает два окна.

public class BlackJackProject {

public static int final_total_cards = 0;
public static int total_cards = 0;

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here

   int turns = 3;

   boolean isGameOver = false;
       while(isGameOver = true){
           turns --;
           if (turns > 0){
               Hit_Or_Stand.main(null);
           }
           else{
               break;
           }
       }
   }
}

Вот код для файла, который открывает два окна

public class Hit_Or_Stand extends javax.swing.JFrame {

   int turns = 3;

   String name = null;
   int balance = 5000;
   int bet_amount = 0;
   String name_and_choice_question = JOptionPane.showInputDialog(null, "What is your name?");
   String ask_bet_amount = JOptionPane.showInputDialog(null, "Your balance is: " + balance + "Enter your bet amount");

public Hit_Or_Stand() {
    initComponents();
     lblOption.setText(name_and_choice_question + ", what would you like to do?");
}

/**
 * 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() {

    jPanel1 = new javax.swing.JPanel();
    lblOption = new javax.swing.JLabel();
    btn_Hit = new javax.swing.JButton();
    btn_Stand = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    lblOption.setText("da");

    btn_Hit.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    btn_Hit.setText("Hit");
    btn_Hit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btn_HitActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(btn_Hit, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                    .addGap(175, 175, 175)
                    .addComponent(lblOption)))
            .addContainerGap(299, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(35, 35, 35)
            .addComponent(lblOption)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 308, Short.MAX_VALUE)
            .addComponent(btn_Hit, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))
    );

    btn_Stand.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    btn_Stand.setText("Stand");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btn_Stand, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 81, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(btn_Stand, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 101, Short.MAX_VALUE))
    );

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

private void btn_HitActionPerformed(java.awt.event.ActionEvent evt) {                                        


    if (final_total_cards < 21){ 
       int card_draw = (int)(Math.random() * 6 + 1);
       total_cards = total_cards + card_draw;
       final_total_cards = total_cards + card_draw;
       JOptionPane.showMessageDialog(null, "Your total card value is: " + final_total_cards);


    }else if (final_total_cards == 21){

        JOptionPane.showMessageDialog(null, "Your total card value is: " + final_total_cards);
        JOptionPane.showMessageDialog(null, "You win!");

        balance = balance + Integer.parseInt(ask_bet_amount);
        JOptionPane.showMessageDialog(null, "Your final balance is : " + balance);
            this.dispose();





    }

    else if (final_total_cards > 21){

        JOptionPane.showMessageDialog(null, "Your total card value is: " + final_total_cards);
        JOptionPane.showMessageDialog(null, "You lose!");

        balance = balance - Integer.parseInt(ask_bet_amount);
        JOptionPane.showMessageDialog(null, "Your final balance is: " + balance);




    }

}                                       

/**
 * @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 ("Windows".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Hit_Or_Stand.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Hit_Or_Stand.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Hit_Or_Stand.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Hit_Or_Stand.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 Hit_Or_Stand().setVisible(true);
        }
    });





}



// Variables declaration - do not modify                     
private javax.swing.JButton btn_Hit;
private javax.swing.JButton btn_Stand;
private javax.swing.JPanel jPanel1;
public static javax.swing.JLabel lblOption;
// End of variables declaration                   

}

1 Ответ

0 голосов
/ 12 марта 2019

Проблема в этом блоке:

   while(isGameOver = true){
       turns --;
       if (turns > 0){
           Hit_Or_Stand.main(null);
       }
       else{
           break;
       }
   }

Пара проблем:

while (isGameOver = true)

Вы не сравниваете, а присваиваете isGameOver для true.Это должно быть ==, но в этом случае вы никогда не войдете в цикл, потому что создали экземпляр переменной false и никогда не изменили значение.

       turns --;
       if (turns > 0){
           Hit_Or_Stand.main(null);
       }
       else{
           break;
       }

Вы начинаете с turns = 3 и уменьшаете его(новое значение 2).Hit_Or_Stand.main(null) вернется сразу после настройки JFrame.Таким образом, у вас сразу будет следующая итерация, снова уменьшите turns (теперь это 1), откройте другое окно.После этого turns снова уменьшается (новое значение теперь 0), и поскольку turns больше не > 1, вы оставляете while -попад.

Чтобы рассказать вам больше о том, какрешение этой проблемы зависит от того, чего вы на самом деле хотите достичь, поэтому вы можете соответствующим образом отредактировать свой вопрос.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...