1

我在这里遗漏了一些东西。我的程序在要求此人输入他们的服务包后结束。请原谅多余的代码,我是这方面的初学者,还没有学到比这更有效的方法。

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);

    }
}
4

1 回答 1

2

您应该尝试将您的字符串与equals(或更好的equalsIgnoreCase)方法进行比较。

正如这里所解释的:Java String.equals 与 ==,在 java 中,“==”运算符检查两个变量是否指向同一个对象,而不是它们是否具有相同的值。

所以如果你写

String a1 = "A";
String a2 = "A"; 

然后

if (a1 == a2) {
  // This is not executed
}
if (a1.equals(a2)) {
  // This is executed
}

这是一个重要的区别,它存在于每个对象中,但大多数人都被字符串欺骗了,因为它是您比较的第一个对象。

通常人们从比较数字开始,而在 Java 中,原始数字(int、long 等)可以与 == 进行比较,因为它们不是对象。

希望这会有所帮助,祝你好运!

于 2013-02-20T13:28:36.620 回答