访问数组Java [英] Accessing an array java

查看:115
本文介绍了访问数组Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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);

当我使用以下方法时:

static void randomWord(String [] array, int number){
     System.out.println(array[number]);
}

控制台会打印出null,但我不确定为什么.如何获得控制台以打印出与smallWordDictionary数组中的元素相对应的字符串?

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?

推荐答案

当长度大于maxWordlength时,您不会在smallWordDictionary[i]中存储任何内容.

You're not storing anything in smallWordDictionary[i] when the length is more than maxWordlength.

您的数组成员的默认值为null,而不是空字符串. (任何引用类型的数组成员的默认值为null.)

The default value for your array members is null, not empty string. (The default value for any array members of reference type is null.)

因此,您的某些随机索引将指向仍为null的数组成员.

Consequently, some of your random indices will point to an array member that is still null.

解决方案包括:

  • 构建一个较小的数组,该数组仅包含通过的单词.没有空值.
  • 在每个未通过的成员中放置一个空字符串.
  • 打印时检查是否为空.

构建较小的阵列

最简单的方法是使用列表.

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[] );

请注意,countsmallerWords.size()smallerWordDictionary.length相同.

在每个未通过的成员中放置空字符串

for(int i=0;i<dictionary.words.length;i++){
    if(dictionary.words[i].length() <=maxWordlength){
        count++;
        smallWordDictionary[i]=dictionary.words[i]; 
    }
    else {
        smallWordDictionary[i]=""; 
    }
}

打印时检查是否为空

static void randomWord(String [] array, int number){
    String member = array[number];
    System.out.println( (null == member) ? "" : member);
}

这篇关于访问数组Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆