2011-11-01 159 views
2

好吧,我試圖讓文件掃描儀返回數組itemList。 但是,我不明白爲什麼每次我返回itemList並嘗試使用println表單。 它返回:打印陣列

[Ljava.lang.String;@3d3b5a3a 

[Ljava.lang.String;@10cb42cf 

[Ljava.lang.String;@482d59a3 

[Ljava.lang.String;@18f42160 

當我讀它的文件中包含的東西一樣

蘋果10

魚20

import java.io.*; 
import java.util.*; 

class loadInventory{ /*This class is used for loading the inventory */ 

private String[] itemList; /*The lines of the inventory are stored in this array */ 
private int numItems;  /* The number of items is stored in this variable */ 

public loadInventory(String fileName){ /*We can do everything in the constructor. It gets the fileName from the superMarket 
               object */ 

itemList = new String[100]; /*We assume there are not more than 100 items in the inventory */ 
numItems=0;     /*initialize numItems to 0*/ 
         /*Read the file using the try-catch block below. We are not specifically catching any exception. 
           We will not cover reading or writing of files and exceptions in this unit. So you 
           don't need to understand this piece of code. */ 
try{ 
    BufferedReader reader = new BufferedReader(new FileReader(fileName)); /*standard code for reading a file */ 
    String line = reader.readLine();  /*read the next line from the file and store in line */ 
    while (line != null){     /*as long as there are lines */ 
      itemList[numItems]= line;   /*store the line in the current location of the array */ 
      numItems++;      /*increment the number of items */ 
      line = reader.readLine();   /*read the next line */ 
     } 

     reader.close();   /*close the reader */ 
    } catch (IOException e){  /*we don't catch any exception */ 
     } 
     System.out.println(itemList); 
    } 

    public String[] getItemList() { 
     return itemList; 

    } 


} 

回答

3

打印實例的數組是這樣的:

System.out.println(Arrays.toString(itemList)); 
+0

我想講師的代碼並不完美,但我開始考慮將itemlist的數組設置爲100並不是最好的選擇,因爲它對數組中的其他東西返回null。 – yoshifish

0
int length = itemList.length; 

int count =0; 

while(count<length) 
{ 
System.out.println(itemList[count]); 
count++; 
} 

這是迭代列表最簡單的方法。

1

數組本身使用Object中的默認toString(),因此它不打印其內容。您將需要使用java.util.Arrays.toString(Object [])打印出數組的內容(或者自己循環)。

0

因爲你想打印整個數組對象,而這樣做:

System.out.println(itemList); 

相反,你需要打印存儲在數組內的一個字符串元素:

System.out.println(Arrays.toString(itemList)); 
0

不打印直接值爲String[]。這樣使用,

for (int i = 0; i < itemList.length; i++) { 
System.out.println("Value::> " +itemList[i]); 
} 
0

多多關注此代碼

while (line != null) 
{     
     itemList[numItems]= line;   
     numItems++;      
     line = (String)reader.readLine();   
} 

試試這個。