2016-09-25 97 views
1

我正在嘗試讀取文件,將其放入數組並打印出來。將文件複製到數組中(Java)

我不知道我在做什麼錯誤的代碼。我一直在試圖獲得一個解決方案,但是我能找到的所有解決方案都比我們應該使用的更先進......我使用相同的方法編寫了一個以前的程序,但是它是一個Double數組。我似乎無法使其工作的字符串?

當我運行它時,我總是收到[Ljava.lang.String; @ 3d4eac6。

我只是想讓它打印boysNames。 boyNames.txt只是一個文本文件中的200個名字的列表。

有人請幫幫我,或者讓我知道這是否可能?

這是我到目前爲止的代碼

public static void main(String[] args) throws FileNotFoundException { 



    String[] boyNames = loadArray("boyNames.txt"); 
    System.out.println(boyNames); 
} 

public static String[] loadArray(String filename) throws FileNotFoundException{ 
    //create new array 
    Scanner inputFile = new Scanner(new File (filename)); 
    int count = 0; 
    //read from input file (open file) 
    while (inputFile.hasNextLine()) { 
     inputFile.nextLine(); 
     count++; 
    } 
    //close the file 
    inputFile.close(); 

    String[] array = new String[count]; 
    //reopen the file for input 
    inputFile = new Scanner(new File (filename)); 
    for (int i = 0; i < count; i++){ 
     array[i] = inputFile.nextLine();    
    } 
    //close the file again 
    inputFile.close(); 
    return array; 
} 

`

+0

'[Ljava.lang.String; @ 3d4eac6 '......這看起來像是在試圖打印出一個數組。你的代碼對我來說確實很好。什麼是錯誤? –

+0

這就是奇怪的...它爲我編譯,但是當我運行它,它只是打印「[Ljava.lang.String; @ 3d4eac6」 – Scinder

回答

0

Java數組不會覆蓋Object.toString(),所以你得到一個通用[Ljava.lang.String;@3d4eac6(或類似)當您嘗試使用System.out.println()將其打印出來。而是遍歷數組並打印每個值。

for (String boyName : boyNames) { 
    System.out.println(boyName); 
} 

或者,你可以使用Arrays.toString()

System.out.println(Arrays.toString(boyNames)); 

另一種方法是使用String.join()(新的Java 8)

System.out.println(String.join("\n", boyNames)); 
+0

呃有更簡單的方法。 –

+0

['String.join()'](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.CharSequence ...-) 也許? – Asaph

+1

謝謝!!!!這使它工作! – Scinder