gpt4 book ai didi

java - 错误: Variable might not have been initialized?

转载 作者:行者123 更新时间:2023-12-01 11:52:11 25 4
gpt4 key购买 nike

尝试创建一个将 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.");
}

}

} ^ ^

最佳答案

不用担心,我所要做的就是将最后一个 else if 语句更改为 else 语句,以便编译器知道 digitalOne、digitTwo 将始终等于某个值。

关于java - 错误: Variable might not have been initialized?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com