I need help with my ohm's law applet code. can't figure it out!
Ok, here is the code that I wrote but there are couple things wrong and i dont know have figure it out.:((
Code :
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class OhmsLawApplet extends Applet implements ActionListener
{
// declare variables
int amps;
double volt, ohms, index;
Image logo; //declare as Image object
//construct components
Label companyLabel = new Label("Welcome to Ohm's Law Calculator - I=V/R");
Label voltLabel = new Label("Enter the voltage:");
TextField voltField = new TextField(10);
Label ohmsLabel = new Label("Enter the resistance:");
TextField ohmsField = new TextField(10);
Button calcButton = new Button("Calculate");
Label outputLabel = new Label("Click the calculate button to see the amps.");
public void init()
{
setForeground(Color.red);
add(companyLabel);
add(voltLabel);
add(voltField);
add(ohmsLabel);
add(ohmsField);
add(calcButton);
calcButton.addActionListener(this);
add(outputLabel);
}
public void actionPerformed(ActionEvent e)
{
volt = Integer.parseInt(voltField.getText());
ohms = Integer.parseInt(ohmsField.getText());
volt = V / 39.36;
omhs = R / 2;
index = amps / Math.pow(ohms);
outputLabel.setText("Electrical current" + Math.round(index) + ".");
}
}
Re: I need help with my ohm's law applet code. can't figure it out!
Generally in applets you don't want to initialize your instance variables that way. Instead, use the init() method (note that this shouldn't have too much of a performance component, but will make your code much more readable).
The first problem I can see is that in your actionPerformed method, you try using the variables V and R, but they were never declared anywhere (I actually have no idea what they're being used for). You're reading in volts and ohms directly from the textfields, there's no need to calculate anything unless you're trying to convert units (can't think of any that would match those conversion factors, though).
The second problem I can see is that you're only reading in integers for volts and ohms. That could be what you want, but I suspect it would make a lot more sense to read in doubles.
Code :
volt = Double.parseDouble(voltField.getText());
ohms = Double.parseDouble(ohmsField.getText());
The last problem I can see is you forgot to put the exponent for the Math.pow() method. However, in my opinion here it would be quicker just to multiply ohms twice.
Lastly, you're calculating the current incorrectly. The variable index is useless because you already have a variable called amps. Just use that variable. Personally I wouldn't round this value because it's quite unlikely you'll be getting current flow of amps (more commonly current is shown in milli-amps), but you can put the Math.round() back in if it's required.
Code :
amps = volt / ohms;
outputLabel.setText("Electrical current: " + amps + " amps");