Reputation: 47
Please help me with my code!
Problem is most likely located in getValues method.
Everytime I enter 2 values and click the calculate button, it gives me a lot of errors.
I programmed this with NetBeans, which is why the code does not look to 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){
*
* }
*/
Error Message:
run: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1011) at java.lang.Float.parseFloat(Float.java:452) at EnergyForm.getValues(EnergyForm.java:201) at EnergyForm.currentBoxActionPerformed(EnergyForm.java:182) at EnergyForm.access$100(EnergyForm.java:12) at EnergyForm$2.actionPerformed(EnergyForm.java:59) at javax.swing.JTextField.fireActionPerformed(JTextField.java:508) at javax.swing.JTextField.postActionEvent(JTextField.java:721) at javax.swing.JTextField$NotifyAction.actionPerformed(JTextField.java:836) at javax.swing.SwingUtilities.notifyAction(SwingUtilities.java:1664) at javax.swing.JComponent.processKeyBinding(JComponent.java:2879) at javax.swing.JComponent.processKeyBindings(JComponent.java:2926) at javax.swing.JComponent.processKeyEvent(JComponent.java:2842) at java.awt.Component.processEvent(Component.java:6282) at java.awt.Container.processEvent(Container.java:2229) at java.awt.Component.dispatchEventImpl(Component.java:4861) at java.awt.Container.dispatchEventImpl(Container.java:2287) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1895) at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:762) at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:1027) at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:899) at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:727) at java.awt.Component.dispatchEventImpl(Component.java:4731) at java.awt.Container.dispatchEventImpl(Container.java:2287) at java.awt.Window.dispatchEventImpl(Window.java:2719) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:688) at java.awt.EventQueue$3.run(EventQueue.java:686) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) at java.awt.EventQueue$4.run(EventQueue.java:702) at java.awt.EventQueue$4.run(EventQueue.java:700) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:699) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Help would be much appreciated! Thanks.
Upvotes: 0
Views: 157
Reputation: 159784
You are getting an NumberFormatException
as your resistanceBox
JTextField
is empty. Simply supply valid float
values for all fields from which you read values. You could add a simple check before attempting to read the values, e.g.:
if (!resistanceBox.getText().trim().isEmpty()) {
resistanceValue = Float.parseFloat(resistanceBox.getText());
} else {
// TODO: alert that R not supplied...
return;
}
Note for Ohm's Law you typically supply 2 values to get the third:
V = IR
Also to calculate power: P = VI
As resistance R
and power P
can be calculated, you could only use voltage & current as inputs.
Upvotes: 1
Reputation: 4996
The first four lines of getValues all attempt to convert the values in the text fields into floats. Unless all four text fields have data, at least one of these lines is going to throw a NumberFormatException. You should (1) check to see that the particular text field is not empty before trying to parse the float and (2) catch the NumberFormatExceptions to handle the case where the user entered invalid data.
Upvotes: 1