这个程序的作用是;
提示输入测试用例的数量,
然后用户输入作为测试用例的字符串行。
程序是计算每个测试用例中元音的数量。
然后打印出每个测试用例。
顺便说一句,对于这个特定的程序“y”也是一个元音 例如; 测试次数:
4
吉斯萨吉克鲁
bsa uiqsacva
oh qi samsauq sajahhsa
斯卡贾约萨克
答案:
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));
}
}
最佳答案
在读取大量测试用例后执行 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)的内容,并打印它的长度。真的不确定它是否更快,但它更简单。
关于java - 对多个字符串输入中的元音进行计数的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36757103/