java - 我应该使用 substring 来避免 java 数据库中的某个字符串还是有其他方法可以绕过它?

标签 java regex string swing substring

我正在构建一个产品数据库,当我使用更新数据库功能时,我的程序崩溃了。

问题是程序本身抛出的一个字符串。

我从数据库文本文件中检索数据,因为我使用的是 numberformat.getCurrencyInstance 并且它会抛出一个美元符号。所以我抛出了一个异常 String Price = updatePriceTextField.getText().substring(1); 这样它就会绕过文本字段开头的美元符号并将信息发送回 textfile 并保存。

现在它提出了我当前的问题,即:当我输入大于 999 的数字并且达到数千时,它会带上逗号:示例:$3000.00 现在是 $3,000.00 当我尝试将该信息发送回数据库时,它会抛出错误并崩溃。

现在我知道我可以简单地添加另一个子字符串来避免,并解决这样的问题,但是如果对象的价格可以说是:$300000000.00 程序会抛出 2逗号 $300,000,000.00 并且会再次崩溃。那么我应该抛出什么样的异常或命令来绕过这些逗号(除了子字符串)。

很抱歉这篇文章很长,但我尽力解释了这个问题。

import java.util.ArrayList;

/**
 *
 * @author 0103425014
 */
public class EditProduct extends javax.swing.JFrame {

    ProductTextFile txtfile = new ProductTextFile();
    ArrayList<Product> products = txtfile.getProducts();
    /**
     * Creates new form UpdateProduct
     */
    public EditProduct() {
        initComponents();
        for (Product p : products)
            updateComboBox.addItem(p.getCode() + "  " + p.getDescription());
    }

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

        updateComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        updateCodeTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        updateDesTextField = new javax.swing.JTextField();
        updatePriceTextField = new javax.swing.JTextField();
        buttonUpdate = new javax.swing.JButton();
        buttonExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        updateComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateComboBoxActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Select Product to edit:");

        jLabel2.setText("Product Code:");

        jLabel3.setText("Product Description:");

        jLabel4.setText("Product Price:");

        buttonUpdate.setText("UPDATE");
        buttonUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonUpdateActionPerformed(evt);
            }
        });

        buttonExit.setText("EXIT");
        buttonExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonExitActionPerformed(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()
                .addGap(76, 76, 76)
                .addComponent(buttonUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonExit)
                .addGap(104, 104, 104))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2))
                        .addGap(39, 39, 39)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(updateDesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(55, 55, 55)
                        .addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(39, 39, 39)
                        .addComponent(jLabel1)))
                .addGap(0, 126, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addGap(33, 33, 33)
                .addComponent(updateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(updateCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(updateDesTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(updatePriceTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addGap(60, 60, 60)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonUpdate)
                    .addComponent(buttonExit))
                .addContainerGap(73, Short.MAX_VALUE))
        );

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

    private void buttonExitActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        System.exit(0);
    }                                          

    private void buttonUpdateActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:

       Product p = new Product();
       p.setCode(updateCodeTextField.getText());
       p.setDescription(updateDesTextField.getText());
       String price = updatePriceTextField.getText().substring(1);
       p.setPrice(Double.parseDouble(price));
       txtfile.updateProduct(p);

       UpdatedConfirm confirmed = new UpdatedConfirm();
       confirmed.setVisible(true);
       this.setVisible(false);

//       txtfile.updateProduct();
    }                                            

    private void updateComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:

        int si = updateComboBox.getSelectedIndex();
        Product sp = products.get(si);
        updateCodeTextField.setText(sp.getCode());
        updateDesTextField.setText(sp.getDescription());
        updatePriceTextField.setText(sp.getFormattedPrice());

    }                                              

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton buttonExit;
    private javax.swing.JButton buttonUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField updateCodeTextField;
    private javax.swing.JComboBox updateComboBox;
    private javax.swing.JTextField updateDesTextField;
    private javax.swing.JTextField updatePriceTextField;
    // End of variables declaration                   
}

最佳答案

改用JFormattedTextField,这样您只需使用getValue,它就会返回该字段的未格式化值。

参见How to Use Formatted Text Fields了解更多详情

关于java - 我应该使用 substring 来避免 java 数据库中的某个字符串还是有其他方法可以绕过它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26666827/

相关文章:

java - Android PhoneGap 横向崩溃

php - 用于密码分级的正则表达式

sql - 清理VB中的文本字符串

java String.replaceAll 正则表达式问题

arrays - 将动态分配的字符串数组从 C 传递到 Fortran

java - Vaadin 操作一些小部件的几个基本问​​题

Java数组: Difference between Component and Element

javascript - 如何在 JavaScript 中使用正则表达式替换字符串

php - 正则表达式 : find range except for one letter or a range

java - 后端服务器脚本