如何初始化字符串?

时间:2013-11-17 22:58:16

标签: java string initialization

String car; 

    if (type == 'E')
        {fee = rate*50;
         car = "Economy";}

    else if (type == 'M')
         {fee = rate*70;
         car = "Midsize";}


    else if (type == 'F')
        {fee = rate*100;
        car = "Fullsize";}

System.out.println("Car type is " + car);

这是我遇到问题的程序的一部分。我得到'本地变量车可能尚未初始化'。我应该怎么做才能让'汽车'初始化?

5 个答案:

答案 0 :(得分:5)

Java不能保证car将被初始化。您else声明中指定if的个案(car)没有保证。

将其初始化为某个值,例如空字符串。

String car = "";

答案 1 :(得分:0)

通常,您将String设置为null以解决编译错误。

String car = null;

这是因为Java试图保护你不要做你不期望的事情。如果未执行所有if语句,则不会分配变量。要告诉Java,您知道可能会发生这种情况,您只需明确选择将其设置为null

答案 2 :(得分:0)

Java无法分辨你的变量覆盖打印会发生什么,因为它最初指向无处,并且条件中包含了进一步的初始化 根据逻辑将您的汽车变量设置为默认值:“”或null是不错的选项,但它最终取决于您

答案 3 :(得分:0)

我会考虑以另一种方式做到这一点:

switch (type) {
 case 'E':
    fee =rate* 50;
    car = "Economy";
    break;
 case 'M':
    fee =rate* 70;
    car = "Economy";
    break;
 case 'F':
    fee =rate*100;
    car = "Economy";
    break;
 default:
    fee = 0;
    car = "";
}

答案 4 :(得分:0)

如何使用内部Enum类解决此问题。

public class EnumExample {
    public enum CarType {
        E( 50,"Economy" ),
        F( 70, "Midsize" ),
        M( 100, "Fullsize");
        // Add as many as you want

        private int cost;
        private String type;

        CarType(int theCost, String theType) {
            cost = theCost;
            type = theType;
        }

        public int getFee(int rate) {
            return rate*cost;
        }

        public String toString() {
            return type;
        }
    }
    public static void main( String[] args ) {
        String type = "E";
        int rate = 25;

        switch( CarType.valueOf( type ) ) {
            case E:
                System.out.println( "The Car Type is: " + CarType.E );
                System.out.println( "The fee is: " + CarType.E.getFee(rate) );
                break;
            case F:
                System.out.println( "The Car Type is: " + CarType.F );
                System.out.println( "The fee is: " + CarType.F.getFee(rate) );
                break;
            case M:
                // ETC
            default:
                // Use a switch/case so you can add 'no car type' e.g Fee = 0;
        }
    }
}