簡體   English   中英

為什么我的數組由不打印到控制台的方法返回?

[英]Why is my array returned by a method not printing to console?

我正在編寫一個程序,它將 a.txt 文件讀入一個使用方法的字符串數組。 但是,當我嘗試通過在主程序中打印數組來測試我的方法時,什么也沒有發生。 我創建了一個將 txt 文件讀入數組的方法,現在我試圖在主程序中打印這個數組以確保它正常工作。

感謝所有幫助,這是我的代碼:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class P4Test {

    public static void main(String[] args) throws FileNotFoundException {
        
        
        
        // have user enter name for file
        Scanner input = new Scanner(System.in);
        
        System.out.println("Enter the name of the file");
                String nameOfFile = input.nextLine();
                
                
                String[] test = readFile(nameOfFile);
                System.out.println(Arrays.toString(test));
    }

    
    public static String[] readFile(String filename) throws FileNotFoundException 
    {
        
        
        
        //read the file 
    
        Scanner file = new Scanner(new File(filename));
        
        // read number of lines inside file
        
        int numString = 0;
        while (file.hasNextLine());
        {
            ++numString;
            file.nextLine();
        }
        file.close();
        
        // now we read the file into a string array
    Scanner keyboard = new Scanner(new File(filename));
    String[] words = new String[numString];
    
    // using a for loop to read in each line to the array
    
    for (int index = 0; index < numString; ++index) {
        words[index] = keyboard.nextLine();
    }
    keyboard.close();
    return words;
    
    
    }
    
    
    
}

您的代碼非常好,除了這一行:

while (file.hasNextLine());

您需要從 while 循環中刪除該分號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM