在课堂外宣布枚举

时间:2015-04-16 00:44:33

标签: java enums

Billl.java

import java.util.Scanner;

enum Package
{
    BASIC("B"),MODERATE("M"),INTERMEDIATE("I"),ADVANCE("A") ;
    Package pakej;
    private String p;

    private Package(String p)
    {
        this.p=p;
    }
}



class Billl //class bil
{
    private double price;
    private int hour;
    private double totalBill;
    private int totalHour;

    Package pakej;

    public Billl(Package pakej)
    {
        this.pakej=pakej;
    }


    public void setHour(int hour)
    {
        this.hour=hour;
    }


    public void choose()
    {
        switch(pakej)
        {
            case BASIC: price=10;
                    int hour1=10;
                    totalHour = hour-hour1;

                    if(totalHour>0)
                        totalBill=price+(totalHour*2);
                    else
                        totalBill=price;
                    break;

            case MODERATE:  price=20;
                        int hour2=20;
                        totalHour = hour-hour2;

                        if(totalHour>0)
                            totalBill=price+(totalHour*1.5);
                        else
                            totalBill=price;
                        break;

            case INTERMEDIATE:  price=30;
                            int hour3=30;
                            totalHour = hour-hour3;

                            if(totalHour>0)
                                totalBill=price+(totalHour*1);
                            else
                                totalBill=price;
                            break;

            case ADVANCE:   price=50;
                        int hour4=50;
                        totalHour = hour-hour4;

                        if(totalHour>0)
                            totalBill=price+(totalHour*0.5);
                        else
                            totalBill=price;
                        break;

            default : System.out.println("Wrong choice");
        }
    }

    public double getBill()
    {
        return totalBill;
    }
}

TestBilll.java

import javax.swing.JOptionPane;
import java.util.Scanner;


public class TestBilll
{

    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);

        String e;  //string for enum
        e= JOptionPane.showInputDialog("\nChoose your package : ");
        e=sc.next().toUpperCase();

        Package pakej;
        Billl b=new Billl(pakej);

        System.out.print("\nPlease enter hours : ");

        //enter hours
        int hour=sc.nextInt();
        b.setHour(hour);
        b.choose();

        System.out.println("\n Your Package : " + pakej + "\nYour total bill : " + b.getBill() );

    }
}

在编译TestBilll.java之后出现错误并且说“pakej'变量可能尚未初始化。我该如何修复这个错误?请帮我修复这个错误。谢谢。

1 个答案:

答案 0 :(得分:1)

Package pakej;
Billl b=new Billl(pakej);

应该是

Package pakej = Package.BASIC;
Billl b=new Billl(pakej);