[英]How to rewrite my two methods so I do not get a NullPointerException?
因此,我的任務是為數組編寫兩個簡單的方法:第一個方法,將數組的大小加倍; 第二種方法,找到數組中第一個重復字符串的索引。 主要方法是我的教授寫的,不得更改。 我的問題是我在運行我的代碼時繼續收到 NullPointerException。 我相信它與 Arrays.sort() 或我老師在 main 中的代碼有關,但我被指示:只使用數組(沒有其他數據結構),使用 Arrays.sort() 來查找欺騙的索引,以及不要修改程序中的任何其他內容......有什么辦法可以按照這些說明重寫我的方法嗎?
完整代碼:
import java.io.*;
import java.util.*;
public class Practice
{
static final int CAPACITY = 10;
static final int NOT_FOUND = -1;
public static void main (String[] args) throws Exception
{
if (args.length < 1 )
{
System.out.println("\nusage: C:\\> java Practice <words filename>\n\n"); // i.e. C:\> java Lab2 10Kints.txt 172822words.txt
System.exit(0);
}
String[] wordList = new String[CAPACITY];
int wordCount = 0;
BufferedReader wordFile = new BufferedReader( new FileReader(args[0]) );
while ( wordFile.ready() ) // i.e. while there is another line (word) in the file
{ if ( wordCount == wordList.length )
wordList = upSizeArr( wordList );
wordList[wordCount++] = wordFile.readLine();
} //END WHILE wordFile
wordFile.close();
System.out.format( "%s loaded into word array. size=%d, count=%d\n",args[0],wordList.length,wordCount );
int dupeIndex = indexOfFirstDupe( wordList, wordCount );
if ( dupeIndex == NOT_FOUND )
System.out.format("No duplicate values found in wordList\n");
else
System.out.format("First duplicate value in wordList found at index %d\n",dupeIndex);
} // END OF MAIN
// TWO METHODS
static String[] upSizeArr( String[] fullArr )
{
int size = fullArr.length; //find the length of the arrays
String[] newSizeArr = new String[(2 * size)]; // creates new array, doubled in size
for (int a = 0; a < size; a++) {
newSizeArr[a] = fullArr[a];
}
return newSizeArr;
}
static int indexOfFirstDupe( String[] arr, int count )
{
Arrays.sort(arr);
int size = arr.length;
int index = NOT_FOUND;
for (int x = 0; x < size; x++) {
for (int y = x + 1; y < size; y++) {
if (arr[x].equals(arr[y])) {
index = x;
break;
}
}
}
return index;
}
} // END OF PROGRAM
NullPointerException 的位置:
編輯:這個問題解決了庫代碼中的 NPE,而不是我自己的代碼。
根據堆棧跟蹤的圖像,NPE 發生在Arrays.sort()
。 雖然沒有記錄(我可以看到),但我相信如果數組包含null
,則此方法會拋出 NPE 。 它還能做什么? null
在自然順序中不能有自然位置,因此包含null
的數組不能用Arrays.sort(Object[])
排序。
怎么修? 我看不出對數組進行排序的意義,因此您可以將其省略。 排序意味着第一個重復項的返回索引不是原始數組的有效索引(從排序之前)。 但是,如果您的教授堅持,您可以通過適當使用重載的Arrays.sort(Object[] a, int fromIndex, int toIndex)
來修復Arrays.sort(Object[] a, int fromIndex, int toIndex)
這樣您只需對字符串所在的數組部分進行排序。
我被指示……使用 Arrays.sort() 來查找欺騙的索引
編輯:如果您只需要查找任何重復項, Arrays.sort()
可以提供幫助。 排序后,您知道任何重復項最終都在數組中,彼此並排。 所以現在你只需要將每個元素與下一個元素進行比較,而不是與數組的所有其他元素進行比較,以確定是否存在重復項,如果有則查找一個。 但是,通常已排序數組中的第一個副本與未排序數組中的第一個副本不同。
例如: 未排序數組:
["pig", "cow", "queen", "cow", "bee", "bee"]
第一個副本: cow
。 cow
第一個索引:1。
排序后:
["bee", "bee", "cow", "cow", "pig", "queen"]
第一個副本: bee
。 bee
第一個索引:0。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.