簡體   English   中英

如何將此FOR循環轉換為WHILE循環,以便它也計入輔音? (JAVA)

[英]How do I convert this FOR loop into a WHILE loop so that it also counts for Consonants? (JAVA)

如何將此FOR循環轉換為WHILE循環,以便它也計入輔音? 到目前為止,我知道如何使用While循環進行基本的計數器...

import java.util.Scanner;

public class VowelsCount {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Input a string: ");
        String str = in.nextLine();

        System.out.print("Number of Vowels in the string: " + vowCount(str) + "\n");
    }

    public static int vowCount(String str) {
        int count = 0;
        for (int index = 0; index < str.length(); index++) {
            if (str.charAt(index) == 'a' || str.charAt(index) == 'e' ||
                str.charAt(index) == 'i' || str.charAt(index) == 'o' ||
                str.charAt(index) == 'u') {
                count++;
            }
        }
        return count;
    }
}

while()循環的參數中帶有termination statement ,這意味着除了初始化和遞增索引外,還必須將終止設置為while參數。 編輯 index變量必須在循環之前初始化。

在您的情況下:

while(index != str.length()){
     //rest of the statement, those from your for loop
     index++;
}

這是現成的LetterCount類,可以封裝所有glogic的字母計數:

public final class LetterCount {

    private final String str;
    private final int vowel;
    private final int consonant;

    public static LetterCount create(String str) {
        int[] count = count(str);
        return new LetterCount(str, count[0], count[1]);
    }

    private static int[] count(String str) {
        int i = str.length();
        int[] count = new int[2];

        while (--i >= 0) {
            char ch = Character.toLowerCase(str.charAt(i));

            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                count[0]++;
            else if (ch >= 'a' && ch <= 'z')
                count[1]++;
        }

        return count;
    }

    private LetterCount(String str, int vowel, int consonant) {
        this.str = str;
        this.vowel = vowel;
        this.consonant = consonant;
    }

    public String getStr() {
        return str;
    }

    public int getVowel() {
        return vowel;
    }

    public int getConsonant() {
        return consonant;
    }

}

您可以通過初始化另一個變量來計數輔音,如果不滿足條件,則在else條件下將其加1。 對於while循環,您可以執行以下操作。

int countVow = 0;
int index = 0;
while(index != str.length())
{
    if(vowel)
    {
        countVow++;
    }

    index++
}
int countCon = index = countVow;

這是一個函數count ,它使用while循環對輔音和元音進行計數(盡管這種循環實際上並不重要):

import java.util.Scanner;

public class VowelsCount {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);

        System.out.print("Input a string: ");
        String str = in.nextLine();

        Counts counts = count(str);

        System.out.println("Number of Vowels in the string: " + counts.getVowels());
        System.out.println("Number of Consonants in the string: " + counts.getConsonants());
    }

    public static Counts count(String str) {
        int vowCount = 0;
        int consCount = 0;

        str = str.toLowerCase();

        int i = str.length();
        while(i-- > 0) {
            char ch = str.charAt(i);
            if(ch >= 'a' && ch <= 'z') {
                switch(ch) {
                    case 'a':
                    case 'e':
                    case 'i':
                    case 'o':
                    case 'u':
                        vowCount++;
                        break;
                    default:
                        consCount++;
                        break;
                }
            }
        }

        return new Counts(vowCount, consCount);
    }

    public static final class Counts {
        private int vowels;
        private int consonants;

        public Counts(int vowels, int consonants) {
            this.vowels = vowels;
            this.consonants = consonants;
        }

        public int getVowels() {
            return vowels;
        }

        public int getConsonants() {
            return consonants;
        }
    }
}

基本上,該函數的工作方式是:遍歷字符串中的所有字符(反向),然后首先檢查它是否是字母(在az之間),如果是,則它必須是元音或輔音 因此,我們只需要檢查哪一個並增加相應的計數器即可。

這工作正常:

public static int vowCount(String str) {
            int count = 0;
            int index = 0;
            while (index < str.length()) {
                if (str.charAt(index) == 'a' || str.charAt(index) == 'e' || str.charAt(index) == 'i' || str.charAt(index) == 'o' || str.charAt(index) == 'u') {
                    count++;
                }
                index++;
            }
            return count;
        }

更換for一個while不需要也算輔音。
兩者都可以做到這一點,並且for設計了更好的迭代方法,直到特定的索引對您的用例而言更好。

想法是定義一個元音字符串和一個輔音字符串,並針對每個遇到的字符,根據這些String的匹配來增加計數器。

static final String vowels = "aei...";
static final String consonants = "bcdf...";

public static int[] vowCount(String str){
  int countV = 0;
  int countC = 0;
  for (int index = 0; index < str.length(); index++){
    String currentChar = str.substring(index, index+1);
    if (vowels.contains(currentChar)){
     countV++;
    }
    else if (consonants.contains(currentChar)){
     countC++;
    }
  }

  return new int[]{countV, countC};
}

我返回了一個int[]數組,但您也可以返回一個Count類的實例,您可以定義該實例來保存這兩個數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM