简体   繁体   English

如何将此FOR循环转换为WHILE循环,以便它也计入辅音? (JAVA)

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

How do I convert this FOR loop into a WHILE loop so that it also counts for Consonants? 如何将此FOR循环转换为WHILE循环,以便它也计入辅音? I know how to do a basic counter using While loop so far... 到目前为止,我知道如何使用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;
    }
}

A while() loop has at its argument a termination statement , that means instead of initialising, and incrementing your index you have to set your termination as while parameter. while()循环的参数中带有termination statement ,这意味着除了初始化和递增索引外,还必须将终止设置为while参数。 EDIT the index variable has to be initialised before your loop. 编辑 index变量必须在循环之前初始化。

In your case: 在您的情况下:

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

This is ready LetterCount class, that could incapsulate all glogic for letter count: 这是现成的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;
    }

}

You can count consonants by initializing another variable, add it by 1 in else condition when your if criteria is not met. 您可以通过初始化另一个变量来计数辅音,如果不满足条件,则在else条件下将其加1。 for while loop you can do something like this. 对于while循环,您可以执行以下操作。

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

    index++
}
int countCon = index = countVow;

Here is a function count that counts both consonants and vowels, using a while loop (although the kind of loop doesn't matter really): 这是一个函数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;
        }
    }
}

Basically, how the function works is that it loops over all the characters in the string (in reverse), and then first checks if it is a letter (between a and z ), and if it is, then it must be either a vowel or a consonant. 基本上,该函数的工作方式是:遍历字符串中的所有字符(反向),然后首先检查它是否是字母(在az之间),如果是,则它必须是元音或辅音 So we just need to check which one and increment the respective counter. 因此,我们只需要检查哪一个并增加相应的计数器即可。

This is working fine:- 这工作正常:

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

Replacing the for by a while is not required to also count the consonants. 更换for一个while不需要也算辅音。
Both can do that and a for that is better designed to iterate until a specific index seems better for your use case. 两者都可以做到这一点,并且for设计了更好的迭代方法,直到特定的索引对您的用例而言更好。

The idea would be to define a String of vowels and a String of consonants and for each encountered character you increment the counter according to the matching of these String s. 想法是定义一个元音字符串和一个辅音字符串,并针对每个遇到的字符,根据这些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};
}

I returned an array of int[] but you could also return an instance of a Count class you can define to hold the two data. 我返回了一个int[]数组,但您也可以返回一个Count类的实例,您可以定义该实例来保存这两个数据。

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

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