gpt4 book ai didi

java - 变量只在 while 循环内才有值?

转载 作者:行者123 更新时间:2023-12-02 00:08:02 25 4
gpt4 key购买 nike

static void parse(String fileName) throws IOException{
FileReader fileReader=new FileReader((fileName));
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder=new StringBuilder();
String string;
StringBuilder myString = null;
while((string = bufferedReader.readLine()) != null) {
myString =stringBuilder.append(string);
String h=myString.toString();
**System.out.println(h);**
}

}




static void parse(String fileName) throws IOException{
FileReader fileReader=new FileReader((fileName));
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder=new StringBuilder();
String string;
StringBuilder myString = null;
while((string = bufferedReader.readLine()) != null) {
myString =stringBuilder.append(string);
String h=myString.toString();
}

**System.out.println(h);**
}

当我尝试代码的第二部分时,它什么也没打印出来。如何在 while 循环之外获取整个 h 字符串?我是否必须将变量 h 声明为实例变量而不是局部变量?

最佳答案

无需创建实例变量。只需将 h 放在循环之外即可:-

static void parse(String fileName) throws IOException{
FileReader fileReader=new FileReader((fileName));
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuilder stringBuilder=new StringBuilder();
String string,h=null;
StringBuilder myString = null;
while((string = bufferedReader.readLine()) != null) {
myString =stringBuilder.append(string);
h=myString.toString();
}
System.out.println(h);
}

关于java - 变量只在 while 循环内才有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13447840/

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