gpt4 book ai didi

java - 为什么我不能在这个 java 程序中打印数组 token[ ] 中的内容

转载 作者:行者123 更新时间:2023-11-29 03:35:41 25 4
gpt4 key购买 nike

程序的整体思路是逐行读取文件并将每个单词保存到数组 token[] 中。我正在尝试使用 for 循环将数组 token[] 中的元素打印到控制台上。但是它说变量 token 还没有被初始化。

import java.io.*;

public class ReadFile{
public static void main(String args[]){
String[] token;
int i;

try{
// Open and read the file
FileInputStream fstream = new FileInputStream("a.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read file line by line and storing data in the form of tokens
while((strLine = br.readLine()) != null){
token = strLine.split(" ");
}
in.close();//Close the input stream
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}

// Why can't I do this printing part?
for(i=0;i<=token.length;i++){
System.out.println(token[i]);
}``
}// close main()
}// close Class

最佳答案

当您在一个方法中时,例如 main,变量声明没有被初始化,您必须自己为它们提供一个初始值。

例如:

字符串[] 数组 = 新字符串[0];

甚至

字符串[]数组=空;

关于java - 为什么我不能在这个 java 程序中打印数组 token[ ] 中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15666207/

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