我过去几天一直在重新学习Java,到目前为止还没有任何问题。我正在尝试编写一段打印句子的示例代码,然后索引程序中的所有字符,最后按顺序显示所有这些字符。但它告诉我这里没有初始化“我”是我得到的代码:
String sentence = "This is a basic sentence sequence using letters and spaces in unicode!";
int index = sentence.offsetByCodePoints(0, i);
int cp = sentence.codePointAt(i);
System.out.println(index);
if (Character.isSupplementaryCodePoint(cp)) i += 2;
else i++;
System.out.println(i);
答案 0 :(得分:1)
但它告诉我这里没有初始化“i”是代码I. 得到:
我假设i
是一个局部变量。在java中,局部变量不会获得默认值。你应该在使用之前初始化它们。
public void localVarTest() {
int i;
System.out.println(i);//error cuz you have not initialized local var i
}
使用默认值初始化它,如:
public void localVarTest() {
int i=0;
System.out.println(i);
}
答案 1 :(得分:1)
得到它我必须像这样初始化“我”:
String sentence = "This is a basic sentence sequence using letters and spaces in unicode!";
int i = 0; // Added this part to the code!
int index = sentence.offsetByCodePoints(0, i);
int cp = sentence.codePointAt(i);
System.out.println(index);
if (Character.isSupplementaryCodePoint(cp)) i += 2;
else i++;
System.out.println(i);
答案 2 :(得分:1)
如果在方法中创建变量,则必须为它们赋值:
int i = 0;
使用(0
/ null
)
答案 3 :(得分:1)
在String语句之后或之前初始化标识符“i”,如:
String sentence = "This is a basic sentence sequence using letters and spaces in unicode!";
int i = 0;
int index = sentence.offsetByCodePoints(0, i);
int cp = sentence.codePointAt(i);
System.out.println(index);
if (Character.isSupplementaryCodePoint(cp)) i += 2;
else i++;
System.out.println(i);
答案 4 :(得分:0)
您应该确保声明并初始化i
,同时确保您有一个名为i
的变量,它的范围对您的代码可见。