错误:变量可能尚未初始化?

时间:2015-02-25 01:46:08

标签: java variables if-statement initialization

尝试创建将RGB颜色代码转换为等效十六进制代码的代码。到目前为止,我只获得了前两个字符的if语句,但是我得到了错误:

ToHex.java:62:错误:变量digitOne可能尚未初始化             System.out.println(“前两个字符是:”+ digitOne + digitTwo);                                                                 ^ ToHex.java:62:错误:变量digitTwo可能尚未初始化             System.out.println(“前两个字符是:”+ digitOne + digitTwo);

到目前为止,这是我的代码的主要部分:

    try{

    int red, green, blue;
    System.out.print("Please enter three numbers representing RGB values: ");
    red = myScanner.nextInt();
    green = myScanner.nextInt();
    blue = myScanner.nextInt();

    if(red>=0 && red<=255 && green>=0 && green<=255 && blue>=0 && blue<=255){
        int firsthexRed = (int)(red/16);
        int redremainder = red%16;
        int firsthexGreen = (int)(green/16);
        int greenremainder = green%16;
        int firsthexBlue = (int)(blue/16);
        int blueremainder = blue%16;
        String digitOne, digitTwo, digitThree, digitFour, digitFive, digitSix;

        if(firsthexRed>=0 && firsthexRed<=9){ //if statement for first hex character
            digitOne = Integer.toString(firsthexRed);
        }else if (firsthexRed==10){
            digitOne = "A";
        }else if (firsthexRed==11){
            digitOne = "B";
        }else if (firsthexRed==12){
            digitOne = "C";
        }else if (firsthexRed==13){
            digitOne = "D";
        }else if (firsthexRed==14){
            digitOne = "E";
        }else if (firsthexRed==15){
            digitOne = "F";
        }

        if(redremainder>=0 && redremainder<=9){ //if statement for second hex character
            digitTwo = Integer.toString(redremainder);
        }else if (redremainder==10){
            digitTwo = "A";
        }else if (redremainder==11){
            digitTwo = "B";
        }else if (redremainder==12){
            digitTwo = "C";
        }else if (redremainder==13){
            digitTwo = "D";
        }else if (redremainder==14){
            digitTwo = "E";
        }else if (redremainder==15){
            digitTwo = "F";
        }

        System.out.println("The first two characters are: "+digitOne+digitTwo);

    }else{
        System.out.println("You did not enter integers between 0-255 (inclusive).");
    }

    }catch(RuntimeException ex){
        System.out.println("Sorry, your input must consist of integers.");
    }

}

} ^                                                                          ^

1 个答案:

答案 0 :(得分:1)

不用担心,我所要做的就是将最后的if语句更改为else语句,这样编译器就知道digitOne,digitTwo总是等于某事。