用于计算多个字符串输入中的元音的程序

时间:2016-04-20 23:40:12

标签: java

这个程序的作用是什么;

提示试验箱数量,
然后用户输入作为测试用例的字符串行 程序是计算每个测试用例中的元音数量。 然后打印出每个测试用例。

对于这个特殊节目而言,“y”也是一个元音 例如;  测试次数:

4
  githsajklu
  bsa uiqsacva
  o h qi samsauq sajahhsa
  skajayyosak

答案:
 5 4 13 2

问题是程序没有读取最后一行/输入。它只是带来了前3个输入的计数,但不是最后一个。我希望我足够清楚

     import java.util.Scanner;
     /*
      * Counts number of Vowels in each line
      */
      public class VowelCount {
     /*
     * 
     */

   public static void main(String[] args){  

    Scanner input = new Scanner(System.in);  
    Scanner input2 = new Scanner(System.in);  

    //prompt user for number of test case     
     System.out.println("Type in number of Test Cases");  
    int testcases = input.nextInt();  

     String[] line = new String[testcases];  
     String newline;  

    for(int i=0; i<testcases; i++)  
    {  
    //initialize input to line 1,2,3 e.t.c  
     line[i] = input2.nextLine();  

     //remove all white spaces   
     newline =line[i].replaceAll(" ", "");  

     display(testcases, newline);  
    }  


}  
/*  
 * counts how many vowels are in eace line of input
 */  

public static int Counter(String input)  
{
    //start count from 0;  
    int counter = 0;  
    for(int i = 0; i<input.length(); i++)  
    {
        //set character at position i to Dstr  
    char dStr = input.charAt(i);  

    //compare if dstr is a vowel  
    if(dStr == 'i' || dStr == 'u' || dStr == 'o' || dStr == 'a' || dStr   == 'e' || dStr == 'y')  
    {
        //increase when characte is a vowel  
        counter++;  
    }
    }
    //return the last count  
    return counter;  
}

/*
 * diplay the total count;
 */
public static void display(int testcases, String input)
{

    System.out.print(" "+Counter(input));
}

}

3 个答案:

答案 0 :(得分:0)

在读取测试用例数量后,执行scan.nextLine()。不知道为什么会这样,有人随意解释,但如果你正在读一个int,那么一个字符串,你可以做到

int n = Integer.parseInt(scan.nextLine());

int n = scan.nextInt();
scan.nextLine();

另外,我知道你没有问,但这是一个更简单的方法来计算元音的数量。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    scan.nextLine();
    for(int i = 0; i < n; i++){
        String str = scan.nextLine();
        System.out.println(str.replaceAll("[^AEIOUaeiouYy]", "").length());
    }
}

这样做是擦除所有不是元音(和y)的东西,并打印出它的长度。真的不确定它是否更快,但它更简单。

答案 1 :(得分:0)

实际上,在这里我正在测试并且它工作得很好,它正在获得我要求的输入数量。

我的控制台:

Type in number of Test Cases
4
werty
 2
sdfghj
 0
xdcfvgh
 0
xsdfgh
 0

答案 2 :(得分:0)

有时,使用较少的代码可以使事情更清晰:

void printVowelCount(String text) {
    System.out.println(text.replaceAll("[^aeiouAEIOU]", "").length());
}