您好我正在编写一个带有一些疯狂逻辑的程序,我有几个循环。我需要访问变量' Sets'在我的第一个循环之外我怎样才能做到这一点?
class Example1 {
public static String sets = new String();
static Set<String> reports(){
try{
String sets = "";
fir(i=1; i<3; i++){
While(bufferedReader.readLine() != null){
if (condition1){
if(condition2){
for(condition3){
if(condition4){
sets = ("test1" + "test2");
for(condition5){
sets = sets.concat("test3");
}
}
}
}
}
}
}
}
}
// ****** I need to access sets here *******
}
答案 0 :(得分:3)
您需要在要使用它们的级别定义要使用的变量。例如如果要在方法的最外层访问它们,则需要在方法的最高级别定义它们,例如:在方法的开头。
BTW:我建议您在IDE中使用格式化程序,以确保您的代码可读。 e.g。class Example1 {
static Set<String> reports() {
Set<String> sets = new HashSet<>();
try {
for (int i = 1; i < 3; i++) {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (condition1) {
if (condition2) {
for (condition3) {
if (condition4) {
sets.add("test1");
sets.add("test2");
for (condition5) {
sets.add("test3");
}
}
}
}
}
}
}
} finally {
}
return sets;
}
}
注意:由于您只是处理数据,使用来自文件的输入和Set的输出,很可能您应该使用Java 8流,但是您的示例中并不清楚您正在尝试做什么