Java,输出没有显示?

时间:2015-02-11 12:46:49

标签: java swing loops output

任务是显示用户全名,随机偶数和首字母。

例如。 Joshua Ethan Paul Smith

SmithJEPS320

当我按下获取代码按钮时没有任何反应,为什么会这样?

package pack;
import javax.swing.JOptionPane;
import java.math.*;



public class saf extends javax.swing.JFrame {



    public saf() {
        initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        btnfullname = new javax.swing.JButton();
        txaDisplay = new javax.swing.JScrollPane();
        TxaDisplay = new javax.swing.JTextArea();
        btnrandomGenerator = new javax.swing.JButton();
        btnCode = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnfullname.setText("Enter");
        btnfullname.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnfullnameActionPerformed(evt);
            }
        });

        TxaDisplay.setEditable(false);
        TxaDisplay.setColumns(20);
        TxaDisplay.setRows(5);
        txaDisplay.setViewportView(TxaDisplay);

        btnrandomGenerator.setText("Generate Random Number");
        btnrandomGenerator.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnrandomGeneratorActionPerformed(evt);
            }
        });

        btnCode.setText("Get Code!");
        btnCode.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCodeActionPerformed(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()
                .addContainerGap(54, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(txaDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(40, 40, 40))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnrandomGenerator)
                        .addGap(112, 112, 112))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnCode)
                        .addGap(165, 165, 165))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(btnfullname)
                        .addGap(177, 177, 177))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(btnfullname)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txaDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnrandomGenerator)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnCode)
                .addContainerGap(28, Short.MAX_VALUE))
        );

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

    private void btnfullnameActionPerformed(java.awt.event.ActionEvent evt) {                                            
    String fullname = JOptionPane.showInputDialog("Enter your full name:");

    TxaDisplay.append(fullname);
    }                                           

    private void btnrandomGeneratorActionPerformed(java.awt.event.ActionEvent evt) {                                                   
    int randnum; //Code for a 3 digit even number
    do
    {
       randnum=(int)(Math.random()*900)+100; 
    }
    while(randnum%2!=0);
    TxaDisplay.append("" + randnum);
    }                                                  

    private void btnCodeActionPerformed(java.awt.event.ActionEvent evt) {                                        
    int randnum = 0 ;
    String fullname = "" ;
    String initials ="";
    int posSpc = fullname.lastIndexOf(" ");
    String surname = fullname.substring(posSpc+1, fullname.length());
    initials = initials + fullname.charAt(0);
    for(int i =0; i< fullname.length() ; i++)
    {
        char ch=fullname.charAt(i);
            if(ch==' ')
            {
                initials = initials + fullname.charAt(i+1);

            }
    }
    String code = surname + initials + "" + randnum;
    TxaDisplay.append(fullname+"\n");
    TxaDisplay.append(code);

    }                                       

    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(saf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(saf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(saf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(saf.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 saf().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextArea TxaDisplay;
    private javax.swing.JButton btnCode;
    private javax.swing.JButton btnfullname;
    private javax.swing.JButton btnrandomGenerator;
    private javax.swing.JScrollPane txaDisplay;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:3)

这很容易。您为空字符串启动全名,然后尝试访问空String的第一个字符 - &gt; StringIndexOutOfBoundException

int randnum = 0 ;
String fullname = "" ;// Here empty string !!!
String initials ="";
int posSpc = fullname.lastIndexOf(" "); // this is always -1
String surname = fullname.substring(posSpc+1, fullname.length()); // This is the empty string
initials = initials + fullname.charAt(0); // That throws a StringIndexOutOfBoundsException

如果您希望这项工作,您需要:

  1. 制作私人变量:private String fullname
  2. 删除所有本地变量fullname并访问类的私有变量
  3. btnCodeActionPerformed中,检查fullname是否为空
  4. 只要fullname为空,
  5. 可能会禁用“获取代码”按钮
  6. 像这样(未经测试):

    public class saf extends javax.swing.JFrame {
    
        private String fullname;
    
    
        public saf() {
            initComponents();
        }
    
    
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            btnfullname = new javax.swing.JButton();
            txaDisplay = new javax.swing.JScrollPane();
            TxaDisplay = new javax.swing.JTextArea();
            btnrandomGenerator = new javax.swing.JButton();
            btnCode = new javax.swing.JButton();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            btnfullname.setText("Enter");
            btnfullname.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnfullnameActionPerformed(evt);
                }
            });
    
            TxaDisplay.setEditable(false);
            TxaDisplay.setColumns(20);
            TxaDisplay.setRows(5);
            txaDisplay.setViewportView(TxaDisplay);
    
            btnrandomGenerator.setText("Generate Random Number");
            btnrandomGenerator.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnrandomGeneratorActionPerformed(evt);
                }
            });
    
            btnCode.setText("Get Code!");
            btnCode.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnCodeActionPerformed(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()
                    .addContainerGap(54, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(txaDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 353, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(40, 40, 40))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(btnrandomGenerator)
                            .addGap(112, 112, 112))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(btnCode)
                            .addGap(165, 165, 165))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(btnfullname)
                            .addGap(177, 177, 177))))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(19, 19, 19)
                    .addComponent(btnfullname)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(txaDisplay, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(btnrandomGenerator)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(btnCode)
                    .addContainerGap(28, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void btnfullnameActionPerformed(java.awt.event.ActionEvent evt) {                                            
        fullname = JOptionPane.showInputDialog("Enter your full name:");
    
        TxaDisplay.append(fullname);
        }                                           
    
        private void btnrandomGeneratorActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        int randnum; //Code for a 3 digit even number
        do
        {
           randnum=(int)(Math.random()*900)+100; 
        }
        while(randnum%2!=0);
        TxaDisplay.append("" + randnum);
        }                                                  
    
        private void btnCodeActionPerformed(java.awt.event.ActionEvent evt) {                        
        if(fullname==null||fullname.trim().isEmpty()) {
              return;
        }
        int randnum = 0 ;
        String initials =;
        int posSpc = fullname.lastIndexOf(" ");
        String surname = fullname.substring(posSpc+1, fullname.length());
        initials = fullname.charAt(0);
        for(int i =0; i< fullname.length() ; i++)
        {
            char ch=fullname.charAt(i);
                if(ch==' ')
                {
                    initials = initials + fullname.charAt(i+1);
    
                }
        }
        String code = surname + initials + "" + randnum;
        TxaDisplay.append(fullname+"\n");
        TxaDisplay.append(code);
    
        }                                       
    
        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(saf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(saf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(saf.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(saf.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 saf().setVisible(true);
                }
            });
        }
    
        // Variables declaration - do not modify                     
        private javax.swing.JTextArea TxaDisplay;
        private javax.swing.JButton btnCode;
        private javax.swing.JButton btnfullname;
        private javax.swing.JButton btnrandomGenerator;
        private javax.swing.JScrollPane txaDisplay;
        // End of variables declaration                   
    }