简体   繁体   中英

Convert String to Double - JAVA

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

        //9


        txtTot.setText(jComboBox1.getSelectedItem().toString());
        tot= Double.parseDouble(txtTot.getText());
        CMB= (Double)jComboBox1.getSelectedItem();
        Total2=tot+CMB;
        txtTot.setText(Double.toString(Total2));

    }   

From the ComboBox I'm setting the jtextfield and the second line I'm taking the string from the textfield and trying to convert it into a double .

Error below:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at test.Test.jComboBox1ActionPerformed(Test.java:392)
    at test.Test.access$600(Test.java:18)
    at test.Test$7.actionPerformed(Test.java:134)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)

To me it seems like you are selecting a value from a combobox then trying to add them together to create a grand total, with the total being updated every time you select a new value from the combobox.

This seems to be working for me, Note I've taken the first line away because it interfered with the existing total.

tot= Double.parseDouble(txtTot.getText());
CMB = Double.parseDouble((String) jComboBox1.getSelectedItem());
Total2=tot+CMB;
txtTot.setText(Double.toString(Total2));

Try to print the txtTot.getText () to the console and check whether it is in proper decimal format. Incorrect format could be the cause of error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM