簡體   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