Hello I am new to Java and NetBeans and am in Advanced classes in which my classes are 5 weeks long, so it is a lot to learn a new code language in 5 weeks. Anyways I have an assignment to Create a class named Movie that holds a movie name and rating. Provide methods to get and set both the movie name and rating. Create a class named TestMovie that creates three Movie instances with different values for name and rating and prints the information about each movie. I have done the code and it is passing the build fine but my professor wants a screen shot of the program working and running but I can't get NetBeans to bring that up. The chapter on building the test project was ripped out of my book. Can I get some help or pointers here is the code I have done:
package movie;
/**
*
* #author Jason
*/
public class Movie {
String movieRating;
public Movie(String rated, String mtitle) {
this.mrating = rated;
this.title = mtitle;
}
public void setRating(String Rating) {
movieRating = Rating;
}
// Get the rating
public String getRating() {
return movieRating;
}
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
#Override
public String toString() {
return "Movie" + " title=" + getTitle() + " rating=" + getRating();
}
public static void main(String args[]) {
Movie mv = new Movie("", "");
mv.toString();
}
private String title;
private String mrating;
}
You can just run a test on the console, that is, create a MovieTest class with only a main method and create three instances/objects of Movie (Movie m1, m2, m3; OR Movie[] movies;). Assign them values either in the constructor or with the set methods then print them out with the method print or println in System.out.
Something along the lines of:
public class MovieTest {
public static void main(String[] args) {
Movie[] movies = new Movie[] {new Movie("R1", "T1"), new Movie("R2", "T2"), new Movie("R3", "T3)";
for (Movie i : movies) {
System.out.println(i.toString());
}
}
}
Then end by screenshooting the results.
As an alternative to the other answers suggesting printing the output to the console, with the Netbeans' UI editor you can easily create a window with a label showing the result, which makes it slightly more fancy.
You can get details on how to this here. Here's an image from that page:
The full working code is here. As you can see, it's just a few extra lines.
Your application prints no output, because you invoke toString(), but you don't print the result of it.
An example to create 3 Movie instances with data,
print them out, and then make a screenshot of your console app.
public static void main(String args[]) {
List<Movie> movieList = new ArrayList<Movie>(3);
Movie mv1 = new Movie("very Good", "Testfilm 1");
movieList add(mv1);
mv1 = new Movie("good", "Testfilm 2");
movieList add(mv1);
mv1 = new Movie("not good", "Testfilm 2");
movieList add(mv1);
for (Movie m : movieList) {
System.out.println(m.toString());
}
}
Related
I was asked in an interview to print title of 2nd last tab if multiple tabs are open.
I tried this later:
LinkedHashSet<String> windows = (LinkedHashSet<String>) driver.getWindowHandles();
ArrayList<String> windowsList = new ArrayList<String>(windows);
int size = windowsList.size();
driver.switchTo().window(windowsList.get(size-2));
System.out.println(driver.getTitle());
The above one is not working correctly, but the below one is working:
driver.switchTo().window(windowsList.get(2));
System.out.println(driver.getTitle());
It is storing the parent window at 0th index but child windows in reverse order. Can someone explain?
WebDriver specification says:
The order in which the window handles are returned is arbitrary.
Even though RemoteWebDriver internally wraps the response with LinkedHashSet (no idea why) the order of what is coming from the WebDriver itself is not predictable.
I would say that since your browser is under your control you do know which tab you opened in which order hence you could keep some map that would associate a handle with the position of that actual tab.
Then you could pick the proper handle from that map by the position.
Could you please provide more valid information? Such as your error report or error log, otherwise I can't better understand the problem you are trying to understand, so I tried it myself, I hope it will help you. Here is the code I constructed with reference to your ideas:
public static void main(String[] args) {
TestDriver driver=new TestDriver("null title");
LinkedHashSet<String> windows = (LinkedHashSet<String>)
driver.getWindowHandles();
ArrayList<String> windowsList = new ArrayList<>(windows);
int size = windowsList.size();
String newTitle = windowsList.get(size - 2);
driver.switchTo().window(newTitle);
System.out.println("driver title:"+driver.getTitle());
System.out.println("window title:"+driver.switchTo().getTitle());
}
TestDriver:
class TestDriver{
public String title;
private TestWindow testWindow;
public TestDriver(String title) {
this.title = title;
}
public TestDriver(String title, TestWindow testWindow) {
this.title = title;
this.testWindow = testWindow;
}
public TestDriver(TestWindow testWindow) {
this.title=testWindow.title;
this.testWindow=testWindow;
}
public HashSet<String> getWindowHandles(){
LinkedHashSet<String> retLinkedHashSet = new LinkedHashSet<>(15);
for (int i = 0; i <15 ; i++) {
retLinkedHashSet.add(i+"");
}
return retLinkedHashSet;
}
/**
* switch
* For convenience, I don't use design patterns.
* #return
*/
public TestWindow switchTo() {
return new TestWindow(this);
}
public void window(String title){
this.title=title;
}
public String getTitle() {
return title;
}
}
TestWindow:
class TestWindow{
public String title;
private TestDriver testDriver;
public TestWindow(String title) {
this.title = title;
}
public TestWindow(TestDriver testDriver) {
this.title=testDriver.title;
this.testDriver = testDriver;
}
public TestDriver switchTo() {
return new TestDriver(this);
}
public void window(String title){
this.title=title;
}
public String getTitle() {
return title;
}
}
This is the first to use your idea, and the final output is as expected.
<div align=center><img src="https://i.stack.imgur.com/7tu2q.png"></div>
Next I'll give you the slightly tweaked code:
estDriver driver=new TestDriver("null title");
LinkedHashSet<String> windows = (LinkedHashSet<String>)
driver.getWindowHandles();
ArrayList<String> windowsList = new ArrayList<>(windows);
int size = windowsList.size();
/* String newTitle = windowsList.get(size - 2);
driver.switchTo().window(newTitle);*/
/**
* In the conversion I always create a new object for assignment.
* split a method,you can got a right question.
*/
String newTitle = windowsList.get(size - 2);
TestWindow testWindow = driver.switchTo();
System.out.println("driver title:"+driver.getTitle());
System.out.println("window title:"+driver.switchTo().getTitle());
}
}
Then you will find:
<div align=center><img src="https://i.stack.imgur.com/frIw0.png"></div>
So the real thing that might get you wrong might be in #link{
In method:switchTo()}, if your transition uses a newly created class, you cannot call it again when you finally output the result, which will cause your result to reset.
The information you gave may be too little for me and I may not be able to actually recover your mistakes, hope this helps.
enter image description here
enter image description here
//Represents list books command for biblioteca
public class ListBooksCommand implements Command {
private static final String BOOKS = "Books::";
private static final String FORMAT = "%-35s %-35s %-35s";
private static final String HEADER = String.format(FORMAT, "Name", "Author", "YearPublished");
private static final String NO_BOOKS_AVAILABLE = "No Books Available";
private final Biblioteca biblioteca;
private final IO io;
public ListBooksCommand(Biblioteca biblioteca, IO io) {
this.biblioteca = biblioteca;
this.io = io;
}
#Override
public void execute() {
if (this.biblioteca.isEmpty(Book.class)) {
this.io.println(NO_BOOKS_AVAILABLE);
return;
}
this.displayBooks();
}
private void displayBooks() {
this.io.println(BOOKS);
this.io.println(HEADER);
this.io.println(this.biblioteca.representationOfAllLibraryItems(Book.class));
}
}
public class ListMoviesCommand implements Command {
private static final String Movies = "Movies::";
private static final String FORMAT = "%-35s %-35s %-35s";
private static final String HEADER = String.format(FORMAT, "Name", "Director", "YearPublished");
private static final String NO_BOOKS_AVAILABLE = "No Movies Available";
private final Biblioteca biblioteca;
private final IO io;
public ListBooksCommand(Biblioteca biblioteca, IO io) {
this.biblioteca = biblioteca;
this.io = io;
}
#Override
public void execute() {
if (this.biblioteca.isEmpty(Movie.class)) {
this.io.println(NO_MOVIES_AVAILABLE);
return;
}
this.displayMovies();
}
private void displayMovies() {
this.io.println(MOVIES);
this.io.println(HEADER);
this.io.println(this.biblioteca.representationOfAllLibraryItems(MOVIE.class));
}
}
I have two classes here one is listbooks command , listmovies command both acts on biblioteca. Both Book and Movie is of type LibraryItem(interface).
Both below codes are same. Both will ask biblioteca to get the representation of its own type. And both commands will display the representation.
This is biblioteca implementation
//Represents a library
public class Biblioteca {
private final List<LibraryItem> allLibraryItems;
public String representationOfAllLibraryItems(Class<? extends LibraryItem> itemType) {
return this.allLibraryItems
.stream()
.filter(libraryItem -> libraryItem.getClass().equals(itemType))
.map(LibraryItem::representation)
.collect(Collectors.joining(LINE_SEPARATOR));
}
public boolean isEmpty(Class<? extends LibraryItem> itemType) {
return this.allLibraryItems.stream().noneMatch(libraryItem -> libraryItem.getClass().equals(itemType));
}
}
Please suggest me a pattern to avoid duplication.
Note: I'm not aware about your requirements. I'm just proposing some general design observations in this answer.
Observation 1: Biblioteca being a library, has library items. In your case, the items in the library are Movie items and Book items. So the library has two main types of items (or it can even contain more. Doesn't matter). Hence the member of Biblioteca should be:
private HashMap<Class<? extends LibraryItem>, List<LibraryItem>> libraryItems;
A map that has item type as Key and List<LibraryItem> as value.
Biblioteca should also contain querying methods that will return the representations for a given item type and representations for all item types. So in my view, Biblioteca class should look like this:
public class Biblioteca {
private HashMap<Class<? extends LibraryItem>, List<LibraryItem>> libraryItems;
public Biblioteca(HashMap<Class<? extends LibraryItem>, List<LibraryItem>> libraryItems) {
this.libraryItems = libraryItems;
}
/*
* Representation of a given type
*/
public String representationOfLibraryItemType(Class<? extends LibraryItem> itemType) {
if(libraryItems.containsKey(itemType)) {
return libraryItems.get(itemType).stream()
.filter(libraryItem -> libraryItem.getClass().equals(itemType))
.map(LibraryItem::representation)
.collect(Collectors.joining(System.lineSeparator()));
} else {
throw new IllegalArgumentException("Missing type " + itemType.getSimpleName());
}
}
/*
* Representation of all types
*/
public List<String> representationOfAllLibraryItems() {
return libraryItems.values()
.stream()
.flatMap(list -> list.stream()
.map(LibraryItem::representation))
.collect(Collectors.toList());
}
}
The method representationOfLibraryItemType should be taking in a Class of item type for filtering. If the item type is found in the library, return it's representations or else throw an exception saying it's an unknown item type.
On the other hand, representationOfAllLibraryItems() should not take any input parameters. It should return all the available representations in the library.
Observation 2: Your LibraryItem should be an abstract class and each of the items in your library should extend this particular class. Because Movie is-a LibraryItem and Book is-a LibraryItem. Now, each of your items can override representation() method which is an abstract method in LibraryItem. Your LibraryItem class should look something like this:
public abstract class LibraryItem {
abstract String representation();
}
Observation 3: Your Book and Movie classes should be independent of Biblioteca because they are just items in-a Library. Today they are in a library called Biblioteca and tomorrow they can be in a library called CentralHallLibrary. So, your item class should be looking something like this:
/*
* Book Item
*/
public class Book extends LibraryItem {
private String title;
private String author;
private String publishedYear;
public Book(String title, String author, String publishedYear) {
this.title = title;
this.author = author;
this.publishedYear = publishedYear;
}
#Override
public String representation() {
/*
* I'm just returning a call to toString
* from this method. You can replace it
* with your representation logic.
*/
return toString();
}
#Override
public String toString() {
return "Book [title=" + title + ", author=" + author + ", publishedYear=" + publishedYear + "]";
}
}
/*
* Movie Item
*/
public class Movie extends LibraryItem {
private String title;
private String director;
private String releaseYear;
public Movie(String title, String director, String releaseYear) {
this.title = title;
this.director = director;
this.releaseYear = releaseYear;
}
#Override
public String representation() {
/*
* I'm just returning a call to toString
* from this method. You can replace it
* with your representation logic.
*/
return toString();
}
#Override
public String toString() {
return "Movie [title=" + title + ", director=" + director + ", releaseYear=" + releaseYear + "]";
}
}
Observation 4: I didn't find any use of the Command class which you are using. Because, as I see, your Command class has only one method called execute() that is used for displaying the representations. Generally I would put such "displaying" code in my client side (UI). If Command class has no other functions other than only printing stuff, it's not necessary in my opinion.
Testing the design: Let's create few Book items and few Movie items and then add those to the Biblioteca library
Book effJava = new Book("Effective Java", "Josh Bloch", "2008");
Book cloudNativeJava = new Book("Cloud Native Java", "Josh Long", "2017");
Book java9modularity = new Book("Java 9 Modularity", "Paul Bakker", "2017");
Movie gotgV2 = new Movie("Guardians of the Galaxy Vol. 2", "James Gunn", "2017");
Movie wonderWoman = new Movie("Wonder Woman", "Patty Jenkins", "2017");
Movie spiderHomeCmg = new Movie("Spider-man Homecoming", "Jon Watts", "2017");
List<LibraryItem> bookItems = new ArrayList<>();
List<LibraryItem> movieItems = new ArrayList<>();
bookItems.add(java9modularity);
movieItems.add(spiderHomeCmg);
bookItems.add(cloudNativeJava);
movieItems.add(wonderWoman);
bookItems.add(effJava);
movieItems.add(gotgV2);
HashMap<Class<? extends LibraryItem>, List<LibraryItem>> store = new HashMap<>();
store.put(Movie.class, movieItems);
store.put(Book.class, bookItems);
//CREATE STORE
Biblioteca bibloiteca = new Biblioteca(store);
Now, on querying the library for all representations -
List<String> allLibraryItemsRep = bibloiteca.representationOfAllLibraryItems();
Will return a result having both Movie and Book representations.
On querying the library for specific item types -
String movieRep = bibloiteca.representationOfLibraryItemType(Movie.class);
String bookRep = bibloiteca.representationOfLibraryItemType(Book.class);
Will return specific representations -
Movie [title=Spider-man Homecoming, director=Jon Watts, releaseYear=2017]
Movie [title=Wonder Woman, director=Patty Jenkins, releaseYear=2017]
Movie [title=Guardians of the Galaxy Vol. 2, director=James Gunn, releaseYear=2017]
Book [title=Java 9 Modularity, author=Paul Bakker, publishedYear=2017]
Book [title=Cloud Native Java, author=Josh Long, publishedYear=2017]
Book [title=Effective Java, author=Josh Bloch, publishedYear=2008]
On querying the library for the type which is not present in the library -
String carRep = bibloiteca.representationOfLibraryItemType(Car.class);
Will throw an exception -
java.lang.IllegalArgumentException: Missing type Car
I understand that this is quite a lengthy answer and hope this brought some clarity about the design.
You can create a generic class ListItemsCommand which will accept the item name or class as a parameter for listing and checking for empty list.
And then call ListItemsCommand with the item type like Movie or Book
If you want to remove duplication I suggest using a collect with groupingBy. This allows you to specify which is the key used for deduplication (or grouping) and a reduction function which in case of a duplicate selects the element which is to be selected from the set of duplicates.
Here is a sample method with the groupingBy collector:
public String representationOfAllLibraryItems(Class<? extends LibraryItem> itemType) {
return this.allLibraryItems
.stream()
.filter(libraryItem -> libraryItem.getClass().equals(itemType))
.collect(Collectors.groupingBy(LibraryItem::getName, LinkedHashMap::new,
Collectors.reducing((o1, o2) -> o1.toString().compareTo(o2.toString()) < 0 ? o1 : o2)))
.values()
.stream()
.map(Optional::get)
.map(LibraryItem::representation)
.collect(Collectors.joining(LINE_SEPARATOR));
}
Here is a small test in which we de-duplicate by name of the movie and select the most recent entry in the data:
public static void main(String[] args) {
List<LibraryItem> items = Arrays.asList(new Movie("Valerian", "Luc Besson", "2017"),
new Movie("Valerian", "Luc Besson", "2016"),
new Movie("Spiderman", "Sam Raimi", "2002"),
new Movie("Spiderman", "Sam Raimi", "2001"),
new Movie("Spiderman", "Sam Raimi", "2003"));
Biblioteca biblioteca = new Biblioteca(items);
System.out.println(biblioteca.representationOfAllLibraryItems(Movie.class));
}
The result looks like this:
Luc Besson - Valerian - 2017
Sam Raimi - Spiderman - 2003
Here the de-duplication happens by movie name and the most recent movie is selected.
I'm having issues creating the following two methods using an ArrayList object:
existTextbook(): checks whether a given textbook is in the catalogue. existTextbook() accepts the title and the author and returns true or false. True if the textbook is in the catalogue, false otherwise.
deleteTexbook(): deletes a textbook from the catalogue. deleteTextbook() accepts a textbook title as parameter and deletes the textbook if it exists.
Searching the Java API, the closest method I can find for the first method is the contains method but it takes an object as a parameter, not a String object within the Textbook object like the title or author. The same is true for the remove method for the second method taking an object of the ArrayList as a parameter.
Any hints on how to have a method look at each Textbook object String title or author, then return true if a match is found, or to delete the Textbook object containing the Textbook object String title or author?
Here's my code so far:
Textbook Class
package Ex1;
import java.text.NumberFormat;
public class Textbook
{
private String category, title, author;
private int year;
private double price;
public Textbook (String category, String title, String author, int year,
double price)
{
this.category = category;
this.title = title;
this.author = author;
this.year = year;
this.price = price;
}
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = "Category: " + category + "\n";
description += "Title: " + title + "\n";
description += "Author: " + author + "\n";
description += "Year: " + year + "\n";
description += "Price: " + fmt.format(price) + "\n" + "\n";
return description;
}
}
Catalogue Class
package Ex1;
import java.util.ArrayList;
public class Catalogue
{
private ArrayList <Textbook> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Textbook>();
}
public void addTextbook (Textbook t)
{
catalogue.add(t);
}
public boolean existTextbook(String title, String author)
{
}
public void deleteTextbook(String title)
{
}
public String toString()
{
return catalogue.toString();
}
}
Driver Class
package Ex1;
public class Drivermain
{
public static void main(String[] args)
{
Textbook javaBook = new Textbook ("Computer Science",
"Java Software Solutions", "Lewis/Loftus", 2015, 163.45);
Textbook dataBook = new Textbook ("Computer Science",
"Data Structures and Algorithm Analysis in Java,",
"Mark A. Weiss", 2015, 181.90);
Textbook calcBook = new Textbook ("Mathematics",
"Calculus Plus NEW MyMathLab", "Briggs/Cochran/Gillett",
2015, 236.90);
Textbook osBook = new Textbook ("Computer Science",
"Operating Systems: Internals and Design Principles",
"William Stallings", 2015, 205.70);
Textbook historyBook = new Textbook ("History",
"History of the Canadian Peoples: Beginnings to 1867, Vol. 1",
"Conard/Finkel/Fyson", 2015, 96.90);
Catalogue bookCatalogue = new Catalogue();
bookCatalogue.addTextbook(javaBook);
bookCatalogue.addTextbook(dataBook);
bookCatalogue.addTextbook(calcBook);
bookCatalogue.addTextbook(osBook);
bookCatalogue.addTextbook(historyBook);
System.out.println(bookCatalogue);
bookCatalogue.existTextbook("Java Software Solutions", "Lewis/Loftus");
bookCatalogue.deleteTextbook("Java Software Solutions");
}
}
I think instead of using methods from collections, you may want to deal with looking in your Arraylist yourself.
I'm not using a for each loop (just a for loop) because for delete it will cause a concurrent modification exception.
package Ex1;
import java.util.ArrayList;
public class Catalogue
{
private ArrayList <Textbook> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Textbook>();
}
public void addTextbook (Textbook t)
{
catalogue.add(t);
}
public boolean existTextbook(String title, String author)
{
for(int i =0; i<catalogue.Size(); i++){
Textbook t = catalogue.get(i);
//you'll want getter and setter methods
if(t.author.equals(author)&&t.title.equals(title))
return truel
}
}
public void deleteTextbook(String title)
{
for(int i =0; i<catalogue.Size(); i++){
Textbook t = catalogue.get(i);
if(t.title.equals(title)){
catalogue.remove(i);
}
}
}
public String toString()
{
return catalogue.toString();
}
}
Happy Coding! Leave a comment if you have any questions.
Instead of directly using those methods you may consider just looping through the catalogue ArrayList yourself and testing if the current object matches the title (and author).
It might be overkill, but you could make Textbook implement Comparable or write a Comparator.
I have searched high and low for a solution to this problem, and finally signed up here to see if someone can point me to what is undoubtedly a really simple solution that is evading me. I'm working on MIT's OpenCourse to teach myself Java and am stumped on this problem.
I have two classes, Library and Book. The program keeps track of books created for each library, their location, and whether or not they are checked out. I am given the main method for Library that cannot be edited. Instead its methods must be built to produce the desired output. The issue I am having is determining the argument syntax to pass to a method in Library that creates a new Book in the main method of Library.
Relevant Library Code:
package mitPractice;
public class Library {
String library_address;
static String library_hours = "Libraries are open daily from 9AM to 5PM";
Book[] catalog;
//List of Methods for Libraries
public Library(String address) {
library_address = address;
}
public static void printOpeningHours() {
System.out.println(library_hours);
}
public void addBook(/*unsure what parameter to add here*/) {
catalog[ (catalog.length + 1)] = //unknown parameter
}
public static void main(String[] args) {
//Create two libraries
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
//Add four books ***This block of code is the problem and is uneditable
firstLibrary.addBook(new Book("A Game of Thrones"));
firstLibrary.addBook(new Book("Rama"));
firstLibrary.addBook(new Book("Understanding Space"));
firstLibrary.addBook(new Book("Way of the Clans"));
So my question is how to make the method compatible with the code given in the main method? I have attempted numerous combinations for arguments to pass to addBook() and none seem to deliver.
Book code:
package mitPractice;
public class Book {
Boolean isCheckedOut = false;
String book_title;
public Book(String title) {
book_title = title;
}
public void Borrow() {
isCheckedOut = true;
}
public void Return() {
isCheckedOut = false;
}
public boolean isBorrowed() {
if (isCheckedOut == true) {
return true;
} else {
return false;
}
}
public String getTitle() {
return book_title;
}
/*public static void main(String[] args) {
Book example = new Book("A Game of Thrones");
System.out.println("Title: " + example.getTitle());
System.out.println("Borrowed?: " + example.isBorrowed());
example.Borrow();
System.out.println("Borrowed?: " + example.isBorrowed());
example.Return();
System.out.println("Borrowed?: " + example.isBorrowed());
}*/
}
You want the parameter to be of type Book:
public void addBook(Book newBook) {
catalog[(catalog.length + 1)] = newBook;
}
This will throw an ArrayIndexOutOfBoundsException though, because you're trying to put an element in the array after the last index. You'll need to keep track of how many books have been added and rebuild your array when it gets full. Like this:
private int numberOfBooks = 0;
public void addBook(Book newBook) {
numberOfBooks++;
if(numberOfBooks >= catalog.length) {
// Rebuild array
Book[] copy = new Book[catalog.length * 2]
for(int i=0; i<catalog.length; i++){
copy[i] = catalog[i];
}
catalog = copy;
}
catalog[numberOfBooks] = newBook;
}
Or use a collection like java.util.ArrayList.
So instead of having this line:
Book[] catalog;
You might have
ArrayList<Book> catalog = new ArrayList<Book>();
This creates an ArrayList which is a Java implementation of a dynamically sized array.
Then your addBook method might look like this:
public void addBook(Book newBook) {
catalog.add(newBook);
}
In order to use ArrayList you'll need to include this line at the beginning of the file, after the package mitPractice; line:
import java.util.ArrayList;
This always ends in array out of bounds :
public void addBook(/*unsure what parameter to add here*/) {
catalog[ (catalog.length + 1)] = //unknown parameter
}
Actually, the best would be to use List :
public class Library {
List<Book> catalog = new ArrayList<>();
...
}
Then you can simply do this :
public void addBook(Book book) {
catalog.add(book);
}
Try this code. This will add a book to a very important data structure called an ArrayList found in the util package in java. A programmer has to import this before the class statement but after any package statement. The code also uses a method from your Book API to print the title when a book is successfully added to the ArrayList. ArrayLists are favourable over Arrays because an java.util.ArrayList can expand without problems whereas an Array is a fixed size and is not so dynamic.
Check out this code I modified of the Library class that compiles and runs.
package mitPractice;
import java.util.ArrayList;
public class Library {
String library_address;
static String library_hours = "Libraries are open daily from 9AM to 5PM";
ArrayList<Book> books = new ArrayList<Book>();
//List of Methods for Libraries
public Library(String address) {
library_address = address;
}
public static void printOpeningHours() {
System.out.println(library_hours);
}
public void addBook(Book b/*unsure what parameter to add here*/) {
books.add(b); // add the book to the ArrayList
System.out.println("The book: " + b.getTitle() + " was successfully added.");
}
public static void main(String[] args) {
//Create two libraries
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
//Add four books ***This block of code is the problem and is uneditable
firstLibrary.addBook(new Book("A Game of Drones"));
firstLibrary.addBook(new Book("Raman Noodles"));
firstLibrary.addBook(new Book("Understanding Space"));
firstLibrary.addBook(new Book("Way of the Yoga Baywatch Babes"));
} // end main
} // end Library class
I hope this helps some.
All the best,
user_loser
After developing in PHP for a long time I have decided to step into Java. Comfortable in OOP methodology and all that, I'm trying to start off at that point within java, but I'm getting hung up on passing out my arraylist object into a for statement to be printed back out using the Item class methods.
HelloInvetory.java
package helloInventory;
import java.util.Arrays;
public class HelloInventory {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
}
Inventory.java
package helloInventory;
import java.util.*;
/**
* Tracks and maintains all items within the inventory
* #author levi
*
*/
public class Inventory {
List<Object> InventoryItems = new ArrayList<Object>();
/*
* create object from Items class
* and insert into Object[] array.
*/
public void createItemObj(int sku, String name, String descriptor, float price) {
Items item = new Items();
item.setSku(sku);
item.setItemName(name);
item.setItemDescription(descriptor);
item.setItemPrice(price);
this.setInventoryItems(item);
}
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
public void setInventoryItems(Object inventoryItems) {
//InventoryItems.add(inventoryItems);
this.InventoryItems.add(inventoryItems);
}
}
Items.java
package helloInventory;
/**
* Class object to hold each item details
* #author levi
*
*/
public class Items {
int sku;
String itemName;
String itemDescription;
float itemPrice;
public int getSku() {
return sku;
}
public void setSku(int sku) {
this.sku = sku;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public float getItemPrice() {
return itemPrice;
}
public void setItemPrice(float itemPrice) {
this.itemPrice = itemPrice;
}
}
Where I am stuck is within the HelloInventory.java
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
IDE (Eclipse) gives me the error "Can only iterate over an array or an instance of java.lang.Iterable". Is there something extra I need, or I'm I going around this totally the wrong way in Java? Correct example would be helpful.
Best,
Levi
You have a very strange architecture here my friend. You shouldn't be using generic Objects everywhere, but the actual types. First thing:
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
Why not just return the List itself?
public List<Item> getAllInventoryItems() {
return this.InventoryItems;
}
Also change this:
List<Item> InventoryItems = new ArrayList<Item>();
and this:
public void setInventoryItems(Item inventoryItems) {
this.InventoryItems.add(inventoryItems);
}
Now iterating the List is smooth sailing:
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Item> InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Item item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
Btw, I changed Items to Item out of habit. A class name should indicate a single entity so by convention it's singular.
Now don't take this the wrong way, but you may have got off on the wrong foot with Java, so I highly recommend this reading: http://www.mindview.net/Books/TIJ/ This worked for me when I was starting with Java, maybe others can suggest some good sources as well.
Ok, two things. One is that Tudor is absolutely right, it's best to use the classes you're expecting directly, not Objects, and stylistically his points are accurate too.
Two is that if you really have to use a list of object, you'll need to cast back from object to whatever type it is that you're expecting to receive.
List<Object> list = inv.getAllInventoryItems();
for (Object item : list){
System.out.println((Items) item).getItemName();
}
However, I wouldn't recommend doing this as it effectively takes what should be a compile-time error and makes it a RunTime error (if the class cannot be cast).