Reputation: 29
I'm missing something here. My program ends after asking the person to input their service package. Please forgive the redundant code, I'm a beginner at this and haven't yet learned more efficient methods than this.
import javax.swing.JOptionPane;
public class InternetSP
{
public static void main(String[] args)
{
final double PACKA = 9.95, PACKB = 13.95, PACKC = 19.95;
final int PACKAC = 2, PACKBC = 1;
double chargecalc, entrycalc = 0;
String entry, pack;
pack = JOptionPane.showInputDialog(null, "Please enter your service" + " package (A,B or C)");
if (pack == "A" || pack == "B")
{
entry = JOptionPane.showInputDialog(null, "Please enter your usage " + "hours.");
entrycalc = Double.parseDouble(entry);
}
if (pack == "A")
{
if (entrycalc > 10)
{
chargecalc = (PACKA + (entrycalc * PACKAC));
JOptionPane.showMessageDialog(null, "Your total charges are: $" + chargecalc);
}
else
{
JOptionPane.showMessageDialog(null, "Your total charge is: $" + PACKA);
}
}
else if (pack == "B")
{
if (entrycalc > 20)
{
chargecalc = (PACKB + (entrycalc * PACKBC));
JOptionPane.showMessageDialog(null, "Your total charges are:" + "$ " + chargecalc);
}
else
{
JOptionPane.showMessageDialog(null, "Your total charge is: $" + PACKB);
}
}
else if (pack == "C")
{
JOptionPane.showMessageDialog(null, "Your total charge is:" + "$ " + PACKC);
}
System.exit(0);
}
}
Upvotes: 1
Views: 76
Reputation: 13367
You should try comparing your string with the equals (or better, equalsIgnoreCase) method.
As explained here : Java String.equals versus == , in java the "==" operator checks whether two variables points to the same Object, not if they have the same value.
So if you write
String a1 = "A";
String a2 = "A";
then
if (a1 == a2) {
// This is not executed
}
if (a1.equals(a2)) {
// This is executed
}
This is an important distinction, it exists for every Objects, but most people are tricked by Strings because it is one of the first Objects that you compare.
Usually people start by comparing numbers, and in Java, the primitive numbers (int, long, etc...) can be compared with == because they are not object.
Hoping this helps, good luck !
Upvotes: 2