嵌套如果在Java中的Else语句和我的格式化它们? (初学者)

时间:2016-09-19 21:36:29

标签: java if-statement

我很抱歉打扰到这里的任何人,但我似乎无法弄清楚为什么我的代码没有运行。我试过上网和我的教科书,但我显然错过了一些可能正好盯着我看的东西。我再次为此简单道歉。任何帮助表示赞赏。

import javax.swing.*;
/**
 *
 * @author Potato
 */
public class MannPass4 
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        // Declerations
        double packageA, packageB;
        double aPrice = 9.95, bPrice = 13.95, cPrice = 19.95;
        double hoursA = 10, hoursB = 20, rHours, holdOption, holdHours;
        final int A_ADDIT = 2, B_ADDIT = 1;

    holdOption = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the cuctomer's package (A, B, or C):"));

    holdHours = Double.parseDouble(JOptionPane.showInputDialog(null, "Enter the number of hours used:"));

        if (holdOption == 'A')
        {
        rHours = (holdHours - hoursA);
        packageA = ((rHours * A_ADDIT) + aPrice);
        JOptionPane.showMessageDialog(null, "The charges are "+ packageA);
        } 
        else if(holdOption == 'B')
        {
        rHours = (holdHours - hoursB);
        packageB = ((rHours * B_ADDIT) + bPrice);
        JOptionPane.showMessageDialog(null, "The charges are "+ packageB);
        }       

        else if (holdOption == 'C')
        {
        JOptionPane.showMessageDialog(null, "The charges are "+ cPrice);
        }

                else 
                {
                 JOptionPane.showMessageDialog(null, "Invalid choice, please choose either A, B, or C.");
                }     
        }    
    }

1 个答案:

答案 0 :(得分:2)

您正在将holdOption解析为double,而它实际上应该是String。稍微修改您的代码:

// Declarations
double packageA, packageB;
double aPrice = 9.95, bPrice = 13.95, cPrice = 19.95;
double hoursA = 10, hoursB = 20, rHours, holdHours;
final int A_ADDIT = 2, B_ADDIT = 1;

String holdOption = JOptionPane.showInputDialog(null,
        "Enter the cuctomer's package (A, B, or C):");

holdHours = Double.parseDouble(JOptionPane.showInputDialog(null,
        "Enter the number of hours used:"));

switch(holdOption)
{
    case "A":
        rHours = (holdHours - hoursA);
        packageA = ((rHours * A_ADDIT) + aPrice);
        JOptionPane.showMessageDialog(null, "The charges are " + packageA);
        break;
    case "B":
        rHours = (holdHours - hoursB);
        packageB = ((rHours * B_ADDIT) + bPrice);
        JOptionPane.showMessageDialog(null, "The charges are " + packageB);
        break;
    case "C":
        JOptionPane.showMessageDialog(null, "The charges are " + cPrice);
        break;
    default:
        JOptionPane.showMessageDialog(null,
            "Invalid choice, please choose either A, B, or C.");
        break;
}