gpt4 book ai didi

java - 无法弄清楚为什么某些变量不会初始化

转载 作者:行者123 更新时间:2023-12-03 18:48:21 25 4
gpt4 key购买 nike

public static String produceAnswer(String y) {
int space1Location = y.indexOf(" ");
String value1 = y.substring(0, space1Location - 1);
String value2 = y.substring(space1Location + 3);
String operator = y.substring(space1Location + 1, space1Location + 2);
int underLocation = value2.indexOf("_");
int slashLocation = value2.indexOf("/");
String wholeNum;
String numerator;
String denominator;
if(underLocation != -1) {
wholeNum = value2.substring(0, underLocation);
numerator = value2.substring(underLocation + 1, slashLocation);
denominator = value2.substring(slashLocation + 1);
}
else if(underLocation == -1 && slashLocation != -1) {
numerator = value2.substring(0, slashLocation);
denominator = value2.substring(slashLocation + 1);
wholeNum = "0";
}
else if(underLocation == -1 && slashLocation == -1) {
wholeNum = value2;
numerator = "0";
denominator = "1";
}
return "whole:" + wholeNum + " numerator:" + numerator + " denominator:" + denominator;
}

由于某种原因,我的代码中的 return 语句不起作用。它说变量尚未初始化,这对我来说没有意义,因为我肯定在 if 语句中对它们进行了初始化,对吗?这里有什么问题吗?

最佳答案

当您编写一个没有最终 elseif-else-if... 语句时,编译器不知道是否保证其中一个条件是true,这意味着它不确定您的局部变量是否会被初始化。

您应该将最后一个 else if 更改为 else

if(underLocation != -1) {
wholeNum = value2.substring(0, underLocation);
numerator = value2.substring(underLocation + 1, slashLocation);
denominator = value2.substring(slashLocation + 1);
} else if (underLocation == -1 && slashLocation != -1) {
numerator = value2.substring(0, slashLocation);
denominator = value2.substring(slashLocation + 1);
wholeNum = "0";
} else {
wholeNum = value2;
numerator = "0";
denominator = "1";
}

甚至:

if (underLocation != -1) {
wholeNum = value2.substring(0, underLocation);
numerator = value2.substring(underLocation + 1, slashLocation);
denominator = value2.substring(slashLocation + 1);
} else if (slashLocation != -1) {
numerator = value2.substring(0, slashLocation);
denominator = value2.substring(slashLocation + 1);
wholeNum = "0";
} else {
wholeNum = value2;
numerator = "0";
denominator = "1";
}

因为如果第一个条件为false,我们已经知道underLocation在第二个条件下保证为-1,所以它是足以测试 slashLocation != -1

关于java - 无法弄清楚为什么某些变量不会初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53600583/

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