【发布时间】:2014-04-27 09:10:17
【问题描述】:
在多次尝试按字母顺序对数组进行排序失败后,我意识到我的失败很可能是由于我的字符串数组值之一为空。我尝试了 Arrays.sort() 和 compareTo(),很像这个用户: How to sort a String array alphabetically (without using compareTo or Arrays.sort)
...具有相同的结果,很可能指向我的值之一为空。如何判断我的值之一是否为空?有测试吗?它是如何变为空的?最重要的是,这甚至是正确的问题吗?谢谢。
String[] titleChoice = new String[5];
String title = "", titleString = "";
String[] authorChoice = new String[5];
String author = "", authorString = "";
int[] pageChoice = new int[5];
String page = "", pageInt = "";
String currentTitle;
String currentPage = "";
String formatEntry;
int x = 0;
int numEntered;
int highestTitle = titleChoice.length - 1;
int highestAuthor = authorChoice.length - 1;
int highestPage = pageChoice.length - 1;
final int MAX_ARRAY_SIZE = 5;
boolean notQuit = true;
Arrays.fill(titleChoice, "zzzzzzzzzzz");
Arrays.fill(authorChoice, "zzzzzzzzzzz");
Arrays.fill(pageChoice, 99999999);
Scanner input = new Scanner(System.in);
do
{
System.out.print("Enter the title of a book, or zzz to quit:");
titleChoice[x] = input.next();
if(!titleChoice.equals("zzz"))
{
LibraryBook inputBook = new LibraryBook();
inputBook.setBook(titleChoice[x]);
LibraryBook inputAuthor = new LibraryBook();
System.out.print("Please enter " + titleChoice[x] + "'s author's last name: ");
authorChoice[x] = input.next();
inputAuthor.setAuthor(authorChoice[x]);
LibraryBook inputPages = new LibraryBook();
System.out.println("Please enter " + titleChoice[x] + "'s page count: ");
pageChoice[x] = input.nextInt();
inputPages.setPages(pageChoice[x]);
x = x + 1;
}
else
System.out.println("You have elected to quit the program. Goodbye.");
}
while(((!titleChoice.equals("zzz")) && x < 5) && ((!authorChoice.equals("zzz")) && x < 5)
&& ((!pageChoice.equals("zzz")) && x < 5));
//I just put this in here to see if it would compile
Arrays.sort(titleChoice[x]); }}
【问题讨论】:
-
遍历列表中的所有元素,并使用
null测试每个元素是否相等? -
当你说它失败时,你到底是什么意思?
-
一个有用的技巧是实际读取您得到的异常堆栈跟踪。
-
boolean containsNull = Arrays.asList(array).contains(null); -
我认为您应该首先考虑是否要在数据结构上使用
nulls。您必须处理一些遗留代码吗?您能先不要添加nulls吗?这会更容易并且会获得更好的性能。