问题
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
}
I used this code to store the strings from a dictionary array into an array containing strings with a shorter word length. I now want to pass this array alongside a random number to the following method(to create a randomly generated word):
randomWord(smallWordDictionary, outcome);
When I use the following method:
static void randomWord(String [] array, int number){
System.out.println(array[number]);
}
The console prints out null
and I'm not sure why. How can I get the console to print out a string that corresponds to its element within the smallWordDictionary
array?
回答1:
You're not storing anything in smallWordDictionary[i]
when the length is more than maxWordlength
.
The default value for your array members is null
, not empty string. (The default value for any array members of reference type is null
.)
Consequently, some of your random indices will point to an array member that is still null.
Solutions include:
- Build a smaller array, that includes only the words that passed. No nulls will be present.
- Place empty string in each member that does not pass.
- Check for null when printing.
Build a smaller array
The easiest way to do this is with a List.
List<String> smallWordList = new ArrayList<>;
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordList.add( dictionary.words[i] );
}
}
smallWordDictionary = smallWordList.toArray( new String[] );
Note that count
is the sames as smallerWords.size()
or smallerWordDictionary.length
.
Place empty string in each member that does not pass
for(int i=0;i<dictionary.words.length;i++){
if(dictionary.words[i].length() <=maxWordlength){
count++;
smallWordDictionary[i]=dictionary.words[i];
}
else {
smallWordDictionary[i]="";
}
}
Check for null when printing
static void randomWord(String [] array, int number){
String member = array[number];
System.out.println( (null == member) ? "" : member);
}
来源:https://stackoverflow.com/questions/44292770/accessing-an-array-java