繁体   English   中英

从Java中的(字符串)数组中删除Null元素

[英]Remove Null elements from a (String) Array in Java

大家好,我是Java的新手(一年花3/4的时间)。

因此,我对此并不了解,我可以做一些基本的事情,但是高级概念尚未向我解释,因此有很多东西要学习! 所以请对我一点点但轻松一点...

好的,所以我有这个项目,我需要将文件中的文本行读取到数组中,但只读取满足特定条件的行。 现在,我将这些行读入数组,然后跳过所有不符合条件的行。 我为此使用for循环。 很好,但是当我打印出数组(必填)时,空值会在我跳过单词的所有地方出现。

我将如何专门删除null元素? 我尝试到处查看,但解释已经超出我的范围!

这是我必须专门处理数组的代码:(scanf是扫描器,在几行前创建):

//create string array and re-open file
    scanf = new Scanner(new File ("3letterWords.txt"));//re-open file
    String words [] = new String [countLines];//word array
    String read = "";//to read file

    int consonant=0;//count consonants
    int vowel=0;//count vowels

    //scan words into array
    for (int i=0; i<countLines; i++)
    {
        read=scanf.nextLine();

        if (read.length()!=0)//skip blank lines
        {    
            //add vowels
            if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')
            {
                if (read.charAt(2)=='a'||read.charAt(2)=='e'||read.charAt(2)=='i'||read.charAt(2)=='o'||read.charAt(2)=='u')
                {
                    words[i]=read;
                    vowel++;
                }
            }
            //add consonants
            if (read.charAt(0)!='a'&&read.charAt(0)!='e'&&read.charAt(0)!='i'&&read.charAt(0)!='o'&&read.charAt(0)!='u')
            {
                if (read.charAt(2)!='a'&&read.charAt(2)!='e'&&read.charAt(2)!='i'&&read.charAt(2)!='o'&&read.charAt(2)!='u')
                {
                    words[i]=read;
                    consonant++;
                }
            }

        }//end if

        //break out of loop when reached EOF
        if (scanf.hasNext()==false)
            break;

    }//end for

    //print data
    System.out.println("There are "+vowel+" vowel words\nThere are "+consonant+" consonant words\nList of words: ");

   for (int i=0; i<words.length; i++)
       System.out.println(words[i]);

非常感谢您提供的任何帮助!

只是words数组有一个不同的计数器,只有在添加单词时才增加它:

int count = 0;

for (int i=0; i<countLines; i++) {
  ...
  // in place of: words[i] = read;
  words[count++] = read;
  ...
}

打印单词时,只需从0循环到count


另外,这是检查元音/辅音的一种简单方法。 代替:

if (read.charAt(0)=='a'||read.charAt(0)=='e'||read.charAt(0)=='i'||read.charAt(0)=='o'||read.charAt(0)=='u')

你可以做:

if ("aeiou".indexOf(read.charAt(0)) > -1)

更新:read.charAt(0)是一些字符x 上面的行说在字符串"aeiou"寻找该字符。 indexOf返回字符的位置(如果找到),否则返回-1。 因此,任何> -1都表示x"aeiou"中的字符之一,换句话说, x是元音。

public static String[] removeElements(String[] allElements) {
    String[] _localAllElements = new String[allElements.length];

    for(int i = 0; i < allElements.length; i++)
        if(allElements[i] != null)
            _localAllElements[i] = allElements[i];

    return _localAllElements;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM