我不能为我的生活弄清楚为什么我得到一个“变量键可能没有被初始化”错误。我输入了我的整个代码,因为如果我删除了BufferedReader并将字符串设置为等于我没有得到错误。此外,如果我将BufferedReader部分保留并删除StringBuffer部分,则字符串键初始化就好了。请帮忙! java的新手(以及一般的编程)。
import java.util.*;
import java.io.*;
public class reverseString {
public static void main(String [] args) {
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String cipher = "";
String input = "";
String newCipher;
String ouput = "";
BufferedReader readerKeyword = null;
String key;
try {
readerKeyword = new BufferedReader(new FileReader("keyword.txt"));
} catch (FileNotFoundException fnfex) {
System.out.println(fnfex.getMessage() + " File not found.");
System.exit(0);
}
try {
while ((key = readerKeyword.readLine()) !=null) {
System.out.println(key);
}
} catch (IOException ioex) {
System.out.println(ioex.getMessage() + " Unable to read file.");
System.exit(0);
}
StringBuffer sb = new StringBuffer();
int len = abc.length();
for(int i = len -1;i>=0;i--)
cipher = cipher + abc.charAt(i);
System.out.println(abc);
System.out.println(cipher);
newCipher = sb.append(key + cipher).toString();
System.out.println(newCipher);
System.out.println(removeDuplicates(newCipher));
}
static String removeDuplicates(String newCipher) {
char[] charArr = newCipher.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for(char ch : charArr) {
charSet.add(ch);
}
StringBuffer StrBuf = new StringBuffer();
for(char c : charSet) {
StrBuf.append(c);
}
return StrBuf.toString();
}
}
是否在第28行的while循环中初始化了?
答案 0 :(得分:0)
IDE和编译器在不保证初始化安全/预防措施时显示它。这样做,它应该消失,
BufferedReader readerKeyword = null;
String key = null;
但是,请确保它已初始化。
不能保证初始化,因为它在try-catch块中,如果你得到异常,你可以在没有初始化的情况下通过,因为你正在处理它。