当超出文本行时,如何防止我的代码将 null 打印到命令行?

How to keep my code from printing null to the command line when out of lines of text?

我的代码需要在文件中的文本用完时停止打印。现在它打印出 null 直到它达到 100。我的任务希望它在没有其他内容可打印时停止接收。

import java.io.*;
import java.util.Scanner;
public class TextFileReader {
    
    String[] stringArray = new String [100];
    
    TextFileReader() {
        
    }
    
    TextFileReader(String fileName) {
        
        try {
            
            FileInputStream fis = new FileInputStream(fileName);
            Scanner scan = new Scanner(fis);
        
            for(int i = 0; i < stringArray.length || scan.hasNextLine(); i++) {
                if(scan.hasNextLine()){
                    stringArray[i] = scan.nextLine();
                }   
            }
        }
        
        catch(IOException e) {
            e.printStackTrace();
        }
    }
    
    public String contents(String fileName) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < stringArray.length; i++) {
            sb.append(stringArray[i]);
            }
        return sb.toString();
    }
    
    public void display(String fileName) {
        for(int i = 0; i < stringArray.length; i++) {
            System.out.println(i + ": " + stringArray[i]);
            }
        }
    }
}

你的问题不是你读错了,而是你显示错了。您初始化 stringArray = new String [100]; 意味着它将在开头有 100 个空值。在你读完之后,如果你阅读的内容少于 100 行,你在调用 display(String fileName)

时仍然会有空值

解决方法是当你达到空索引时停止显示

public void display(String fileName) {
    for(int i = 0; i < stringArray.length; i++) {
        if(stringArray[i] == null) break;
        System.out.println(i + ": " + stringArray[i]);
        }
    }
}

它运行 100 次迭代,因为数组的大小为 100 尝试在 while 循环中插入此代码,您会在其中阅读以下行:

if (stringArray[i]==null) break

我还建议将读取的行保存到列表中,因为您不需要限制大小

此解决方案更好,因为您读取的迭代次数多于所需次数,数组中的迭代次数与文件中的行数不匹配