对于书籍数组,任务是从用户那里获取对象的属性,然后根据他们选择的作者、标题或页数进行排序。我的冒泡排序适用于页数,但不适用于用户选择作者或标题时,所以我猜我在参考存储和值存储方面缺少一些东西,也许?谢谢!
import javax.swing.*;
import java.util.*;
public class LibraryBookSort {
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
LibraryBook tempBook = new LibraryBook();
String enteredAuthor = "", enteredTitle = "";
String enteredPageCount;
String sortBy;
String displayString = "";
int parsedSortBy;
int parsedPageCount;
int booksLength = books.length;
// populate the array
for (int x = 0; x < booksLength; ++x)
books[x] = new LibraryBook();
// get property values from user
for (int x = 0; x < booksLength; ++x)
{
enteredTitle = JOptionPane.showInputDialog(null, "Enter book " + (x + 1) + " of 5's title:");
books[x].setTitle(enteredTitle);
enteredAuthor = JOptionPane.showInputDialog(null, "Enter book " + (x + 1) + " of 5's author:");
books[x].setAuthor(enteredAuthor);
enteredPageCount = JOptionPane.showInputDialog(null, "Enter book " + (x + 1) + " of 5's page count:");
parsedPageCount = Integer.parseInt(enteredPageCount);
books[x].setPageCount(parsedPageCount);
}
// sort by property values
sortBy = JOptionPane.showInputDialog("Choose option to sort by: (1) title, (2) author, or (3) page count");
parsedSortBy = Integer.parseInt(sortBy);
while (parsedSortBy < 1 || parsedSortBy > 3)
{
sortBy = JOptionPane.showInputDialog("Invalid selection, please choose option to sort by: (1) title, (2) author, or (3) page count");
parsedSortBy = Integer.parseInt(sortBy);
}
if (parsedSortBy == 1)
{
for (int a = 0; a < booksLength - 1; ++a)
{
for (int b = 0; b < booksLength - 1; ++b)
{
if (books[b].getTitle().compareTo(books[b+1].getTitle()) > 1)
{
tempBook = books[b];
books[b] = books[b+1];
books[b+1] = tempBook;
}
}
}
}
else if (parsedSortBy == 2)
{
for (int a = 0; a < booksLength - 1; ++a)
{
for (int b = 0; b < booksLength - 1; ++b)
{
if (books[b].getAuthor().compareTo(books[b+1].getAuthor()) > 1)
{
tempBook = books[b];
books[b] = books[b+1];
books[b+1] = tempBook;
}
}
}
}
else
{
for (int a = 0; a < booksLength - 1; ++a)
{
for (int b = 0; b < booksLength - 1; ++b)
{
if (books[b].getPageCount() > books[b+1].getPageCount())
{
tempBook = books[b];
books[b] = books[b+1];
books[b+1] = tempBook;
}
}
}
}
for (int i = 0; i < booksLength; ++i)
{
displayString += (books[i].getTitle() + ", by " + books[i].getAuthor() + ". " + books[i].getPageCount() + " pages.\n");
}
JOptionPane.showMessageDialog(null, "Books sorted by your choice:\n\n" + displayString);
}
}