In: Computer Science
This is my java method that is suppose to take data from a file(String, String, Double, Int ) and load that data into an object array. This is what I have and when I try to display the contents of this array it prints a "@" then some numbers and letters. which is not the correct output. any help correcting my method would be much appreciated.
public void loadInventory(String fileName) {
String inFileName = fileName;
String id = null;
String name = null;
double price = 0;
int quantity = 0;
int count = 0;
try {
Scanner infile = new Scanner(new FileInputStream(inFileName));
count = 0;
while (infile.hasNext() && count < 100)
{
id = infile.next();
name = infile.next();
price = infile.nextDouble();
quantity = infile.nextInt();
Item newItemList = new Item(id, name, price, quantity);
itemList[count] = newItemList;
++count;
}//end of hasNext loop
infile.close();
}//end of try
catch (IOException ex)
{
count = -1;
System.out.printf("\nNow ya done goofed " + ex +"\n");
}//end of catch
}
Issue: -------- If the contents of this array it prints a "@" then some numbers and letters. Then you are tying to print Item object without having a toString() method in the Item class. In other words, If you do not have toString() method in a class and you are trying to print the object of such class then it prints the address of object. Address looks like starts with @ and then some numbers and letter. Fix: ------ Add a toString method in Item class. Check the example below. public class Item { private String id; private String name; private double price; private int quantity; public Item(String id, String name, double price, int quantity) { this.id = id; this.name = name; this.price = price; this.quantity = quantity; } public String toString() { return "Item{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", price=" + price + ", quantity=" + quantity + '}'; } } import java.io.FileInputStream; import java.io.IOException; import java.util.Random; import java.util.Scanner; public class TestCode { static Item itemList[] = new Item[100]; public static void loadInventory(String fileName) { String inFileName = fileName; String id = null; String name = null; double price = 0; int quantity = 0; int count = 0; try { Scanner infile = new Scanner(new FileInputStream(inFileName)); count = 0; while (infile.hasNext() && count < 100) { id = infile.next(); name = infile.next(); price = infile.nextDouble(); quantity = infile.nextInt(); Item newItemList = new Item(id, name, price, quantity); itemList[count] = newItemList; ++count; }//end of hasNext loop infile.close(); }//end of try catch (IOException ex) { count = -1; System.out.printf("\nNow ya done goofed " + ex +"\n"); }//end of catch } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String fn; System.out.println("Enter file name: "); fn = scanner.next(); loadInventory(fn); for(int i = 0;i<itemList.length;i++){ System.out.println(itemList[i]); } } }