读取文件时出现问题,程序看起来不错,不理解为什么它输出null



嘿,伙计们,我正试图读入一个文件,我以前已经读过很多次了,但无论中有多少行代码,它都会一直输出"null"。

    public static void main(String[] args) {
        // TODO code application logic here
    Scanner kbd = new Scanner(System.in);
    String[] item = new String[25];
   Scanner fileInput;
   File inFile = new File("dictionary.txt");
    try {
    fileInput = new Scanner(inFile);
    int newItem = 0;
    while (fileInput.hasNext())
    {
      item[newItem++] = fileInput.nextLine();
      System.out.println(item[newItem]);
    }
    }
    catch(FileNotFoundException e){System.out.println(e); }

txt文件。请帮忙。

递增newItem,然后打印item[newItem]。它总是返回null,因为您还没有在item中为新索引写入任何内容。

尝试:

while (fileInput.hasNext()) {
    item[newItem] = fileInput.nextLine();
    System.out.println(item[newItem]);
    newItem++;
}

这是因为newItem++,它返回值,然后递增。

因此,您首先设置项[x]=…;-但是随后打印出项目[x+1];

最新更新