打印arrays

好的,我正在尝试让文件扫描程序返回数组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; } } 

打印像这样的实例数组:

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

数组本身使用Object的默认toString(),因此它不会打印其内容。 您将需要使用java.util.Arrays.toString(Object [])来打印出数组的内容(或者自己循环)。

 int length = itemList.length; int count =0; while(count 

这是迭代列表的最简单方法。

因为您在执行以下操作时尝试打印整个数组对象:

 System.out.println(itemList); 

相反,您需要打印存储在数组中的单个String元素:

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

不要直接打印String[]值。 像这样使用,

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

注意这段代码

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

尝试这个。