当前位置: 首页 > 知识库问答 >
问题:

能源转换器应用程序不起作用,问题可能是在getVal的方法

龚联
2023-03-14

请帮我写代码!

问题很可能出在getValues方法上。

每次我输入 2 个值并单击计算按钮时,都会给我很多错误。

我用NetBeans编写了这个程序,这就是为什么代码看起来不像streamlined。

 /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */

    /**
     *
     * @author cshames
     */
    import java.text.DecimalFormat;
    import java.lang.Math.*;
    public class EnergyForm extends javax.swing.JFrame {
        public static DecimalFormat hundred = new DecimalFormat("0.00");
        public static double voltageValue;
        public static double currentValue;
        public static double resistanceValue;
        public static double powerValue;



        /**
         * Creates new form EnergyForm
         */
        public EnergyForm() {
            initComponents();
        }

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

            voltageBox = new javax.swing.JTextField();
            currentBox = new javax.swing.JTextField();
            resistanceBox = new javax.swing.JTextField();
            powerBox = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            calculateButton = new javax.swing.JButton();
            resetButton = new javax.swing.JButton();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

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

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

            jLabel1.setText("Voltage:");

            jLabel2.setText("Current:");

            jLabel3.setText("Resistance:");

            jLabel4.setText("Power:");

            jLabel5.setFont(new java.awt.Font("Comic Sans MS", 0, 14)); // NOI18N
            jLabel5.setText("Ohm's Law Converter");

            calculateButton.setText("Calculate");
            calculateButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    calculateButtonActionPerformed(evt);
                }
            });

            resetButton.setText("Reset");
            resetButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    resetButtonActionPerformed(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.TRAILING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(66, 66, 66)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(powerBox, javax.swing.GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
                                    .addComponent(resistanceBox))
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap(71, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(calculateButton)
                                        .addGap(33, 33, 33)
                                        .addComponent(resetButton))
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(jLabel1)
                                            .addComponent(jLabel2))
                                        .addGap(18, 18, 18)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(currentBox, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(voltageBox, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(170, 170, 170)))))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(98, 98, 98)
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(21, 21, 21)
                    .addComponent(jLabel5)
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(voltageBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(currentBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(resistanceBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(powerBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(resetButton)
                        .addComponent(calculateButton))
                    .addContainerGap(30, Short.MAX_VALUE))
            );

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

        private void voltageBoxActionPerformed(java.awt.event.ActionEvent evt) {                                           
            getValues();
        }                                          

        private void resistanceBoxActionPerformed(java.awt.event.ActionEvent evt) {                                              
            getValues();
        }                                             

        private void powerBoxActionPerformed(java.awt.event.ActionEvent evt) {                                         
            getValues();
        }                                        

        private void currentBoxActionPerformed(java.awt.event.ActionEvent evt) {                                           
            getValues();
        }                                          

        private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                
            getValues();
        }                                               

        private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
            powerBox.setText(null);
            voltageBox.setText(null);
            currentBox.setText(null);
            resistanceBox.setText(null);
        }                                           

        /**
         * @param args the command line arguments
         */
//help here please! 
       public static void getValues() {
            voltageValue = Float.parseFloat(voltageBox.getText());
            resistanceValue = Float.parseFloat(resistanceBox.getText());
            currentValue = Float.parseFloat(currentBox.getText());
            powerValue = Float.parseFloat(powerBox.getText());
            //if(current==true&&voltage==true){//finds resistance & power
              if(currentBox.getText() != null && voltageBox.getText() != null) { 
                  resistanceValue=voltageValue/currentValue;
                  powerValue=voltageValue*currentValue;
                  String resistanceValueString = hundred.format(resistanceValue);
                  String powerValueString = hundred.format(powerValue);
                  resistanceBox.setText(resistanceValueString);
                  powerBox.setText(powerValueString);

            }
            else if(currentBox.getText() != null && resistanceBox.getText() != null){//finds voltage & power
                voltageValue=resistanceValue*currentValue;
                powerValue=(currentValue*currentValue)*resistanceValue;
                 String voltageValueString = hundred.format(voltageValue);
                  String powerValueString = hundred.format(powerValue);
                  voltageBox.setText(voltageValueString);
                  powerBox.setText(powerValueString);

            }
            else if(resistanceBox.getText() != null && voltageBox.getText() != null){//finds current & power
                currentValue=voltageValue/resistanceValue;
                powerValue=(voltageValue*voltageValue)/resistanceValue;
                 String currentValueString = hundred.format(currentValue);
                  String powerValueString = hundred.format(powerValue);
                  currentBox.setText(currentValueString);
                  powerBox.setText(powerValueString);

            }
            else if(powerBox.getText() != null && voltageBox.getText() != null){//finds current & resistance
                currentValue=powerValue/voltageValue;
                resistanceValue=(voltageValue*voltageValue)/powerValue;
                 String currentValueString = hundred.format(currentValue);
                  String resistanceValueString = hundred.format(resistanceValue);
                  resistanceBox.setText(resistanceValueString);
                  currentBox.setText(currentValueString);

            }
            else if(currentBox.getText() != null && powerBox.getText() != null){//finds voltage & resistance
                voltageValue=powerValue/currentValue;
                resistanceValue=powerValue/(currentValue*currentValue);
                 String resistanceValueString = hundred.format(resistanceValue);
                  String voltageValueString = hundred.format(voltageValue);
                  resistanceBox.setText(resistanceValueString);
                  voltageBox.setText(voltageValueString);

            }
            else if(resistanceBox.getText() != null && powerBox.getText() != null){//finds voltage & current
                voltageValue=Math.sqrt((powerValue*resistanceValue));
                currentValue=Math.sqrt(powerValue/resistanceValue);    
                 String currentValueString = hundred.format(currentValue);
                  String voltageValueString = hundred.format(voltageValue);
                  currentBox.setText(currentValueString);
                  voltageBox.setText(voltageValueString);
            }

        }
        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(EnergyForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(EnergyForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(EnergyForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(EnergyForm.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 EnergyForm().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton calculateButton;
        private static javax.swing.JTextField currentBox;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private static javax.swing.JTextField powerBox;
        private javax.swing.JButton resetButton;
        private static javax.swing.JTextField resistanceBox;
        private static javax.swing.JTextField voltageBox;
        // End of variables declaration                   
    }
    /**
     * if(textfield.getText()!=null&&othertextfield.getText()!=null){
     *     
     * }
     */

错误消息:

run:线程“AWT-event queue-0”Java . lang . numberformatexception:sun . misc . floating decimal . readjavaforomatstring(floating decimal . Java:1011)at Java . lang . float . parse float(float . Java:452)at energy form . get values(energy form . Java:201)at energy form . currentboxactionperform(energy form . Java:182)at energy form . access $ 100(energy form . Java:12

非常感谢帮助!谢了。

共有2个答案

皇甫敏达
2023-03-14

你得到一个 NumberFormatException,因为你的 resistanceBox JTextField 是空的。只需为从中读取值的所有字段提供有效的浮点值。您可以在尝试读取值之前添加一个简单的检查,例如:

if (!resistanceBox.getText().trim().isEmpty()) {
   resistanceValue = Float.parseFloat(resistanceBox.getText());
} else {
   // TODO: alert that R not supplied...
   return;
}

请注意,对于欧姆定律,您通常提供2个值来获得第三个值:

V = IR

也可以计算功率:< code>P = VI

由于可以计算电阻R和功率P,因此只能使用电压

柯锋
2023-03-14

getValue的前四行都试图将文本字段中的值转换为浮点数。除非所有四个文本字段都有数据,否则这些行中至少有一行会抛出NumberFormatExc的异常。在尝试解析浮点数之前,您应该(1)检查特定文本字段是否为空,并且(2)捕获NumberFormatExceptions来处理用户输入无效数据的情况。

 类似资料:
  • 我正在尝试捕捉select标记中的任何更改,并在选择选项时激活一个功能。 html代码: 我正在尝试选择供应商并激活此功能: 由于某种原因,功能尚未激活,有什么建议吗?

  • 我正在尝试使用vue3应用程序中的scss。我有以下错误。 ./src/components/singlepost.vue?vue&type=style&index=0&id=164ef990&lang=scss(./node_modules/css-loader/dist/cjs.js??ref-8-One of-1-1!/node_modules/vue-loader-v16/dist/sty

  • 在我的Spring会话中,我使用了 redis 服务器。现在我正在使用 Angular 7。 这里代码1 2 3 4 > 点击注销按钮后,我的页面将重新加载,但注意happen.it将与上一页相同。 如果我把{headers:headers}放在返回的loginservice中。logout(),则会出现错误 (http.js:167),位于HttpHeaders.push../node_modu

  • 我使用的是来自web应用程序的Spring数据JPA。我的目标是工作API、REST crud方法,使用MySQL中的两个表。项目是目标,那么DB有两个表:Item和AutoBrand,它们是关联关系。一件商品可以得到比一件更多的汽车品牌。但我的应用程序得到的问题,自动品牌表不是从项目表找到id。 项目代表java AutoBrand Rep.Java

  • 这就是我正在做的。 部署此应用程序在 jboss 中失败,因为它在 tomcat 中部署,并且像 charm 一样工作。 我使用来自eclipse的动态web应用程序作为项目源。 将项目导出到war文件并在jboss服务器中部署也不起作用。 web.xml: Spring.xml: 控制器: 和 JBOSS 中的错误:

  • MongoDB不使用索引-可能的排序问题? 我们有一个完全索引的MongoDB查询,最多可以扫描4/5行。然而,查询似乎只使用索引的一个元素(整数),而忽略了字符串部分。 我们使用的是不区分大小写的排序规则(强度=2),但指定与否没有任何区别。文档:https://docs.mongodb.com/manual/core/index-case-insensitive/ 排序规则是否使用索引?有没有