Hi all,
I have to declare an array of LibraryBook objects and sort
them either by title, author or page count, as the user
requests.
I've got the basics down but I'm missing something.
public class LibraryBookSort
{
public static void main(String[] args)
{
LibraryBook[] myBook = new LibraryBook[5];
myBook[0] = new LibraryBook("Java Programming", "Joyce Farrell", 881);
myBook[1] = new LibraryBook("A Book", "E Author", 345);
myBook[2] = new LibraryBook("B Book", "F Author", 450);
myBook[3] = new LibraryBook("C Book", "G Author", 650);
myBook[4] = new LibraryBook("D Book", "H Author", 750);
//below I was just checking if it worked to this point. Its not compiling.
for (int x = 0; x < myBook.length; ++x)
myBook[x].setTitle();
for (int x = 0; x < myBook.length; ++x)
System.out.println(myBook[x].getTitle());
}
// Sort the names alphabetically using a bubble sort and display the results.
// System.out.print("Ascending sort: ");
// display(title);
//}
// ----------------------------------------------------
// Displays the names in the String.
// ----------------------------------------------------
public static void display(String[] title)
{
for (int x=0; x < title.length; ++x)
{
System.out.println(myBook[x] + " ");
}
System.out.println();
}
// ----------------------------------------------------
// Sort the names alphabetically (ascending)
// ----------------------------------------------------
public static void titleSort(String[] title)
{
for (int x=0; x < title.length - 1; ++x)
for (int y=0; y < title.length - 1; ++y)
{
if (title[y].compareTo(title[y+1]) > 0)
{
String temp = title[y];
title[y] = title[y+1];
title[y+1] = temp;
}
}
}
}
import java.util.*;
import javax.swing.*;
public class LibraryBook
{
private String title;
private String author;
private int pageCount;
//contructor
public LibraryBook(String bookTitle, String bookAuthor, int bookpageCount)
{
title = bookTitle;
author = bookAuthor;
pageCount = bookPageCount;
}
//get methods
public String getTitle()
{
return title;
}
public String getAuthor()
{
return author;
}
public int getPageCount()
{
return pageCount;
}
//set methods
public void setTitle(String bookTitle)
{
title = bookTitle;
}
public void setAuthor(String bookAuthor)
{
author = bookAuthor;
}
public void setPageCount(int bookPageCount)
{
pageCount = bookPageCount;
}
}