I have a class Borrower which consists of a name and then it also stores an arraylist full of items that the person has borrowed.
I want to be able to create multiple instances of this class from my main and then be able to access them to view the items they have borrowed.
I am having trouble understanding how to create multiple instances. I just keep running into the issue of overwriting the the Borrowed class.
So in the code below if I create newBorrower("Tim") and then addItem("Wrench"), and then go to create newBorrower("john") then I overwrite newBorrower.
I want to be able to create multiple instances of Borrower based on user input?
I've tried saving the entire Borrower class. I'm not sure if that would work, because it will not sort so I can't add multiple names or I get an error.
Borrower Class
public class Borrower
{
protected String name;
protected String item;
ArrayList<String> itemList = new ArrayList<String>();
public Borrower()
{
}
public Borrower(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void addItem(String item)
{
this.item = item;
itemList.add(item);
}
Main Class
public class WhoBorrowedIt
{
public static void main(String[] args)
{
ArraySortedList<String> borrowersList = new ArraySortedList<String>();
Borrower newBorrower = new Borrower();
Borrower otherBorrower = new Borrower();
Scanner inName = new Scanner(System.in);
Scanner inItem = new Scanner(System.in);
String item;
String name;
String menu;
int option;
menu = "Make a selection: " + "\n"
+ "1. Add Borrower" + "\n"
+ "2. Add Item Borrowed" + "\n"
+ "3. Remove Item Returned" + "\n"
+ "4. View Borrowers" + "\n"
+ "5. Exit";
do
{
Scanner in = new Scanner(System.in);
System.out.println(menu);
option = in.nextInt();
switch(option)
{
case 1: //create borrower
{
System.out.println("Enter Name");
name = inName.nextLine();
newBorrower = new Borrower(name);
borrowersList.add(newBorrower.getName());
break;
}
case 2: //add items
{
System.out.println("Enter item");
item = inItem.nextLine();
System.out.println("Who is borrowing");
name = inName.nextLine();
if(borrowersList.contains(name))
{
newBorrower.addItem(item);
}
else
{
newBorrower = new Borrower(name);
borrowersList.add(newBorrower.getName());
newBorrower.addItem(item);
}
}
}while(option != 5)
}
}
Use a Map like this
if (borrowersMap.containsKey(name))
{
borrowersMap.get(name).addItem(item)
}
else
{
newBorrower = new Borrower(name);
borrowersMap.put(newBorrower.getName(), newBorrower);
newBorrower.addItem(item);
}
where borrowersMap is a HashMap
Map<String, Borrower> borrowersMap = new HashMap<String, Borrower>();
You can change your list to this
List<Borrower> borrowerList = new ArraySortedList<Borrower>();
and then add a method to your program that gets a borrower by name
private Borrower getBorrowerByName( String borrowerName ){
for( Borrower borrower : borrowerList ){
if( borrower.getName().equalsIgnoreCase( borrowerName ) ){
return borrower;
}
}
return null;
}
then when you create a new borrower, you add it to the list - when you get an existing borrower, you use the method and check for null before adding an item to it.
Related
This is the parent class
public class Holding {
private String holdingId, title;
private int defaultLoanFee, maxLoanPeriod, calculateLateFee;
public Holding(String holdingId, String title){
this.holdingId = holdingId;
this.title = title;
}
public String getId(){
return this.holdingId;
}
public String getTitle(){
return this.title;
}
public int getDefaultLoanFee(){
return this.defaultLoanFee;
}
public int getMaxLoanPeriod(){
return this.maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the child class:
public class Book extends Holding{
private String holdingId, title;
private final int defaultLoanFee = 10;
private final int maxLoanPeriod = 28;
public Book(String holdingId, String title){
super(holdingId, title);
}
public String getHoldingId() {
return holdingId;
}
public String getTitle(){
return title;
}
public int getDefautLoanFee(){
return defaultLoanFee;
}
public int getMaxLoanPeriod(){
return maxLoanPeriod;
}
public void print(){
System.out.println("Title: " + getTitle());
System.out.println("ID: " + getHoldingId());
System.out.println("Loan Fee: " + getDefaultLoanFee());
System.out.println("Max Loan Period: " + getMaxLoanPeriod());
}
}
This is the menu:
public class LibraryMenu {
static Holding[]holding = new Holding[15];
static int hold = 0;
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int options = keyboard.nextInt();
do{
}
System.out.println();
System.out.println("Library Management System");
System.out.println("1. Add Holding");
System.out.println("2. Remove Holding");
switch(options){
case 1:
addHolding();
break;
default:
System.out.println("Please enter the following options");
}
}while(options == 13);
System.out.println("Thank you");
}
public static void addHolding(){
System.out.println("1. Book");
System.out.println("2. Video");
int input1 = input.nextInt();
switch(input1){
case 1:
addBook();
break;
case 2:
addVideo();
break;
default:
System.out.println("Please select the following options");
break;
}
}
public static void addBook(){
}
}
All i want is when a user wants to add a book, the user will type in the title and id for it and it will save into the array, and when it is done, it will go back to the menu. I cant seem to do it with my knowledge at the moment.
i tried to do this in the addBook() method
holding[hold] = new Book();
holding[hold].setBook();
the setBook method would be in the Book class, to complete the setBook, i have to make set methods for all the get method. But when i do this, the constructor is undefined.
public void setBook(){
System.out.println("Title: " + setTitle());
System.out.println("ID: " + setHoldingId());
System.out.println("Loan fee: " + setDefaultLoanFee());
System.out.println("Max Loan Period: " + setMaxLoanPeriod());
}
If there is anything wrong with my code, please feel free to say it to me :D
Thanks.
edit: After the user adds a book or video, when the user wants to print all the holdings, it will show the title, id, loan fee and max loan period. How do i do that?
edit2: Clean up a few parts that wasn't necessary with my question
I would suggest you to use "List of Object" concept in handling it.
1) You can define a List of Book object for example.
List<Book> bookList = new ArrayList<Book>();
2) Everytime when you hit AddBook() function, you can then do something like this.
//Create a temporary object of Book to get the user input data.
Book tempBook = new Book(holdingIDParam, titleParam);
//Add them to the list
bookList.Add(tempBook);
3) You can then use that list to your likings, whether to store them into a .txt based database or to use them throughout the program. Usage example:
bookList.get(theDesiredIndex).getBook() ...
I am not entirely sure of what you want but after paying focus on your bold text,this is what I can understand for your case. Feel free to correct me on your requirements if it doesn't meet.
Hope it helps :)
I am trying to read from a file and store the contents into an object called ToDoList(from what I assume is under the GetItem method). Then I am supposed to allow the user to add on to the list. But I am lost on how to create the object and print it.
public class ToDoList {
private ToDoItem[] items;
ToDoItem td = new ToDoItem();
String inputline;
Scanner keyboard = new Scanner(System.in);
int i = 0;
String[] stringArray = new String[100];
private void setItems(ToDoItem[] items) throws FileNotFoundException {
File file = new File("ToDoItems.txt");
Scanner ReadFile = new Scanner(file);
while (ReadFile.hasNext()) {
String ListString = ReadFile.nextLine();
stringArray[100] = (ListString);
}
}
private ToDoItem[] getItems() {
return items;
}
public void addItem(int id, String description) {
stringArray[100] = (td.getId() + td.getDescription());
}
public String[] getAddItem() throws FileNotFoundException {
try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
i++;
stringArray[i] = (td.getId() + ". " + td.getDescription() + "\n");
fout.print(stringArray[i]);
} else {
System.out.println("Here is the list so far:");
}
} while ("y".equals(inputline));
return stringArray;
}
}
#Override
public String toString() {
return "ToDoList{" + "items=" + getItems()
+ '}';
}
I am supposed to use the "getAddItem" method to allow the user to add to the list. But I can't figure out how to add an array to an object. let alone make the object.
A little code to expand on what pininfarina said and to help you get going.
You need a ToDoItem class. Something like this:
public class ToDoItem {
private String id;
private String description;
public ToDoItem(String id, String description) {
this.id = id;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
Then you need a ToDoList class to hold each item. You backed yours with an Array, but I used an ArrayList:
public class ToDoList {
private ArrayList<ToDoItem> items = new ArrayList<ToDoItem>();
public ToDoList(String fileName) throws FileNotFoundException {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNext()) {
String nextLine = scanner.nextLine();
StringTokenizer tokenizer = new StringTokenizer(nextLine, ",");
String id = tokenizer.nextToken();
String description = tokenizer.nextToken();
items.add(new ToDoItem(id, description));
}
} finally {
scanner.close();
}
}
public void setItems(ArrayList<ToDoItem> newItems) {
this.items.addAll(newItems);
}
public List<ToDoItem> getItems() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ToDoList{");
for (ToDoItem item : items) {
builder.append(item.getId() + "," + item.getDescription() + "\n");
}
builder.append("}");
return builder.toString();
}
}
This includes a constructor that reads the file and parses out items. Each line in the file must be something like "1,something" because the tokenizer uses the comma. Note that the Scanner actually destroys the file as it reads it. You might consider using some sort of FileReader instead.
Finally you need a main class to run it. Something like this:
public class RunIt {
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
ToDoList list = new ToDoList("ToDoItems.txt");
try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
String inputLine;
do {
System.out.println("add to the list? [y/n]");
inputLine = keyboard.nextLine();
if ("y".equals(inputLine)) {
System.out.println("enter a to-do using the format 'id,description'");
StringTokenizer tokenizer = new StringTokenizer(keyboard.nextLine(),
",");
String id = tokenizer.nextToken();
String description = tokenizer.nextToken();
list.addItem(new ToDoItem(id, description));
} else {
System.out.println("Here is the list so far:");
System.out.println(list);
}
} while ("y".equals(inputLine));
}
}
}
Please note that there is a lot of room for improvement here (exception handling, more robust file reading, etc), but this should get you started.
You are asking a broad question. Here's some design tips for you.
Create your collection class. This could be named ToDoList. Then create the attributes and behaviors of this class. One attribute will be the collection variable of your to do list items. You can use, List, ArrayList, etc. Behaviors could be add, remove, reorder, and etc.
Create your item class. Again with the attributes and behaviors. Attributes could include what to do, date, importance level, etc.
When you read your file, have your program to instantiate your ToDoItem class for every line, item etc. then save them into the previously created container class which is your ToDoList.
You can use your ToDoList class' addItem method (behavior) to have your users add more items into your ToDoList. If you want to keep the list even after your program closes. You can create a database to store your objects.
Good luck.
I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
So I'm making a program that will store the meetings I've had with some kids I'm tutoring. It'll keep tabs on the meeting times, discussions, and how many hours I've done. I know how to write all the methods to do that, but my issue is that the program will only hold that information for the session that the program is open... how would I go about storing this information and accessing it after the program is closed and opened again?
This is some excerpts from a test score keeper program I did in java class that has this same issue...
public class Student {
private String name;
private int test1;
private int test2;
private int test3;
public Student() {
name = "";
test1 = 0;
test2 = 0;
test3 = 0;
}
public Student(String nm, int t1, int t2, int t3){
name = nm;
test1 = t1;
test2 = t2;
test3 = t3;
}
public Student(Student s){
name = s.name;
test1 = s.test1;
test2 = s.test2;
test3 = s.test3;
}
public void setName(String nm){
name = nm;
}
public String getName (){
return name;
}
public void setScore (int i, int score){
if (i == 1) test1 = score;
else if (i == 2) test2 = score;
else test3 = score;
}
public int getScore (int i){
if (i == 1) return test1;
else if (i == 2) return test2;
else return test3;
}
public int getAverage(){
int average;
average = (int) Math.round((test1 + test2 + test3) / 3.0);
return average;
}
public int getHighScore(){
int highScore;
highScore = test1;
if (test2 > highScore) highScore = test2;
if (test3 > highScore) highScore = test3;
return highScore;
}
public String toString(){
String str;
str = "Name: " + name + "\n" + //\n makes a newline
"Test 1: " + test1 + "\n" +
"Test 2: " + test2 + "\n" +
"Test 3: " + test3 + "\n" +
"Average: " + getAverage();
return str;
}
}
If your data is not too big or complicated - something that you could save in a Rolodex in days gone by - you can save it to a file. Add methods to your class that will format the data properly and write it to a given OutputStream or Writer or whatever. And a method that will read it back.
To write to the file, add an option "save" in your program menu, and when it's chosen, open a file, iterate through your data, and call the saving method for each of your object.
To read from the file, add an option "load" in your program menu, and when it's chosen, open a file, and use your method of reading for each object.
The method for reading can be a static method in the class, that will first see if there are any data in the file and if it can read them properly, and only if it did, will create an object and return it (otherwise return null). There are other options, but this is the one that most encapsulates the needs of the object.
There is also an option to serialize and deserialize each object and put it in an object stream.
If the data is complicated, and there are many objects with various relations between them, you should use a database. This will require learning some database design and SQL.
To demonstrate the file reading/writing idea, add to your Student class:
public void save(PrintWriter outfile) {
outfile.format("%s|%d|%d|%d%n", name, test1, test2, test3);
}
This will write a line with the fields separated by "|" (vertical bar). Of course, you'll have to make sure none of the student names has a vertical bar in it. So you'll need to modify your 4-parameter constructor and your setter:
public Student(String nm, int t1, int t2, int t3) {
name = nm.replaceAll("\\|", "");
test1 = t1;
test2 = t2;
test3 = t3;
}
public void setName(String nm) {
name = nm.replaceAll("\\|", "");
}
Now, to read the file, we add a static method:
public static Student load(BufferedReader infile) throws IOException {
String line;
line = infile.readLine();
// Check if we reached end of file
if (line == null) {
return null;
}
// Split the fields by the "|", and check that we have no less than 4
// fields.
String[] fields = line.split("\\|");
if (fields.length < 4) {
return null;
}
// Parse the test scores
int[] tests = new int[3];
for (int i = 0; i < 3; i++) {
try {
tests[i] = Integer.parseInt(fields[i + 1]);
} catch (NumberFormatException e) {
// The field is not a number. Return null as we cannot parse
// this line.
return null;
}
}
// All checks done, data ready, create a new student record and return
// it
return new Student(fields[0], tests[0], tests[1], tests[2]);
}
You can see that this is more complicated, because you need to check that everything is OK at every step. In any case when things are not OK, we return null but of course, you can decide to just display a warning and read the next line. You'll have to return null when there are no more lines, though.
So, assuming we have a List<Student> students, here is how we write it to a file. I just chose "students.txt" but you can specify a full path leading where you want it. Note how I'm making a backup of the old file before I open the new file. If something goes wrong, at least you have the previous version of the file.
File f = new File("students.txt");
if (f.exists()) {
File backup = new File("students.bak");
if ( ! f.renameTo(backup) ) {
System.err.println( "Could not create backup.");
return;
}
f = new File("students.txt");
}
try ( PrintWriter outFile = new PrintWriter(f);) {
for (Student student : students) {
student.save(outFile);
}
} catch (FileNotFoundException e) {
System.err.println("Could not open file for writing.");
return;
}
After you do this, if you look for the file "students.txt", you will see the records you wrote in it.
How about reading it? Assume we have an empty students list (not null!):
try ( BufferedReader inFile = new BufferedReader(new FileReader(f))) {
Student student;
while ( ( student = Student.load(inFile)) != null) {
students.add(student);
}
} catch (FileNotFoundException e) {
System.err.println( "Could not open file for reading.");
return;
} catch (IOException e) {
System.err.println( "An error occured while reading from the file.");
}
Having done this, you can check your students list, and unless there were errors in the file, all your records will be there.
This is a demonstration, of course. You may want to read into some other collection or instead of printing an error and returning do something else. But it should give you the idea.
You could use db4o for persisting your data. Its an object-database with a spimple api to use. You can store java object read or delete them..
Download it here DB4O
And use the snippets of this tutorial (GER):Tutorial in German
Here is an example:
and Code:
package db4o.example;
public class Student {
String name;
public Student(String name) {
this.name = name;
}
#Override
public String toString() {
return "Student Name: " + name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package db4o.example;
import java.util.List;
import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
public class Main {
public static void main(String[] args) {
ObjectContainer db = Db4oEmbedded.openFile("F:\\studentDB");
saveExample(db);
readAllExample(db);
readExample(db);
deleteAllExample(db);
db.close();
}
private static void deleteAllExample(ObjectContainer db) {
System.out.println("DeleteAllExample Example:");
List<Student> allStudents =readAllExample(db);
for (Student student : allStudents) {
db.delete(student);
}
db.commit();
}
private static List<Student> readAllExample(ObjectContainer db) {
System.out.println("ReadAllExample Example:");
List<Student> allStudents = db.query(Student.class);
System.out.println("Count: " + allStudents.size());
for (Student student : allStudents) {
System.out.println(student);
}
return allStudents;
}
private static void readExample(ObjectContainer db) {
System.out.println("ReadExample Example:");
Student queryStudent = new Student("Max Mustermann");
// Gets all Students named Max Mustermann
List<Student> students = db.queryByExample(queryStudent);
System.out.println("Count: " + students.size());
for (Student student : students) {
System.out.println(student);
}
}
private static void saveExample(ObjectContainer db) {
System.out.println("Save Example:");
Student myStudent = new Student("Max Mustermann");
db.store(myStudent);
db.commit();
}
}
I am trying to add user input to an Arraylist using a do-while loop however I keep ending up with a list consisting of only the final item inputed repeated several times.
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while(!response.equals("done"));
return toBuy;
}
should work as mentioned in my comment.
Please implement a toString() method in your Item class if not done already.
you should replace your System.out.println as following:
public static ArrayList<Item> purchaseItems()
{
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
do {
response = in.nextLine();
if(!response.equals("done") ){
toBuy.add(new Item(response, randGen.nextInt(100)));
}
} while(!response.equals("done"));
for (Item item : toBuy){
System.out.println(item);
}
return toBuy;
}
if this doesn't helps, please share some more code.
Here is fully working example
package stackoverflow;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Q53837506 {
public static void main(String[] args) {
ArrayList<Item> purchaseItems = purchaseItems();
System.out.println(purchaseItems);
}
public static class Item {
String r;
int v;
public Item(String r, int v) {
super();
this.r = r;
this.v = v;
}
#Override
public String toString() {
return "Item [r=" + r + ", v=" + v + "]";
}
}
static final Random randGen = new Random();
public static ArrayList<Item> purchaseItems() {
ArrayList<Item> toBuy = new ArrayList<Item>();
String response;
System.out.println("What would you like to purchase? (type \"done\" to end) ");
Scanner in = new Scanner(System.in);
do {
response = in.nextLine();
if (!response.equals("done")) {
toBuy.add(new Item(response, randGen.nextInt(100)));
System.out.println(toBuy);
}
} while (!response.equals("done"));
return toBuy;
}
}