Java 读取文件后输出中出现Null错误
我正在做这个程序,当我打印时,我在输出的末尾不断得到“null”错误,正如你在代码中看到的那样。它确实可以很好地读取文件,但在最后,它添加了很多空值。任何指导都将不胜感激! 这是我到目前为止试过的Java 读取文件后输出中出现Null错误,java,Java,我正在做这个程序,当我打印时,我在输出的末尾不断得到“null”错误,正如你在代码中看到的那样。它确实可以很好地读取文件,但在最后,它添加了很多空值。任何指导都将不胜感激! 这是我到目前为止试过的 public static void main(String[] args) throws Exception { Stack nifo=new Stack(); FileReader file = new FileReader("infix.dat"); try (Buffe
public static void main(String[] args) throws Exception
{
Stack nifo=new Stack();
FileReader file = new FileReader("infix.dat");
try (BufferedReader br = new BufferedReader(file)) {
String [] words = new String[50];
String text="";
int ctrl = 0;
String Line =br.readLine();
while (Line!= null)
{
words[ctrl]= Line;
Line = br.readLine();
ctrl = ctrl + 1;
}//end of while loop
for (int i = 0; i < words.length; i++)
{
System.out.println(words[i]);
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}//end of catch
}//end of main class
谢谢大家! 您可以声明一个固定大小的数组:
String[] words = new String[50];
然后在其中存储一些值,然后打印每个元素:
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
for(int i=0;i
所有未使用的元素都为空。因此,如果您的文件有6行,它将打印这6行,然后打印44个空值,因为您没有在数组的其他44个插槽中放入任何内容。我建议您使用不同的数据结构,如列表。这将允许您仅存储所需的值的数量
试试这个:
public static void main(String[] args) throws Exception
{
Stack nifo=new Stack();
FileReader file = new FileReader("infix.dat");
try (BufferedReader br = new BufferedReader(file)) {
List<String> words = new LinkedList<>(); //replaced your array with a list
String text="";
String Line =br.readLine();
while (Line!= null)
{
words.add(Line);
Line = br.readLine();
}//end of while loop
for (String word : words)
{
System.out.println(word);
}
file.close();
} catch (IOException e) {
e.printStackTrace();
}//end of catch
}//end of main class
publicstaticvoidmain(字符串[]args)引发异常
{
堆栈nifo=新堆栈();
FileReader文件=新的FileReader(“infix.dat”);
try(BufferedReader br=新的BufferedReader(文件)){
List words=new LinkedList();//将数组替换为列表
字符串文本=”;
String Line=br.readLine();
while(行!=null)
{
添加(行);
Line=br.readLine();
}//while循环结束
for(字符串字:字)
{
System.out.println(word);
}
file.close();
}捕获(IOE异常){
e、 printStackTrace();
}//捕获结束
}//主课结束
由于您不确定数组的大小,如果您想坚持使用数组,那么下面可能会解决您的问题
for (int i = 0; i < words.length && words[i] != null; i++)
{
System.out.println(words[i]);
}
file.close();
for(int i=0;i
只需确保您的循环不会处理words数组中任何索引的空值。因为当您声明一个固定大小的数组时,数组中从未填充过的索引被初始化为null,这不是一个错误,这就是数组中的所有空白。非常感谢您并感谢提供链表提示@迈克很乐意帮忙!如果这解决了您的问题,请记住向上投票并接受答案=]感谢您的输入和快速回答。希望这对您有所帮助,因为我不想用其他数据结构替换您的阵列。但如果你在寻找多样性,还有另一个答案值得一试:)
for (int i = 0; i < words.length && words[i] != null; i++)
{
System.out.println(words[i]);
}
file.close();