import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Vowels
{
public static void main(String[] args) throws FileNotFoundException
{
String vowels = "aeiou";
int[] counters = new int[vowels.length()];
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
console.useDelimiter("");
while (console.hasNext())
{
char ch = console.next().charAt(0);
ch = Character.toLowerCase(ch);
if(ch == 'a')
{
counters[0]++;
}
if(ch == 'e')
{
counters[1]++;
}
if(ch == 'i')
{
counters[2]++;
}
if(ch == 'o')
{
counters[3]++;
}
if(ch == 'u')
{
counters[4]++;
}
}
for (int i = 0; i < vowels.length(); i++)
{
System.out.println(vowels.charAt(i) + ": " + counters[i]);
}
}
}
当我运行文件时,仅当它应同时检测到数百个时,它才检测到3 e。我的代码没有出现任何问题,请提供帮助。我认为它必须在我的定界符和结束之间,因为其余内容不在书中。
最佳答案
您的定界符没有按照您认为的方式工作。假设您打算读取inputFileName
,则可以构造一个File
和Scanner
来这样做(记住要在Scanner
块中或使用finally
statement关闭try-with-resources
)。您还可以通过元音在counters
中的位置来确定正确的vowels
索引。最后,您可以将格式化的io用于输出循环。就像是,
String vowels = "aeiou";
int[] counters = new int[vowels.length()];
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.nextLine().trim();
try (Scanner scan = new Scanner(new File(inputFileName))) {
while (scan.hasNextLine()) {
for (char ch : scan.nextLine().toLowerCase().toCharArray()) {
int p = vowels.indexOf(ch);
if (p >= 0) {
counters[p]++;
}
}
}
}
for (int i = 0; i < vowels.length(); i++) {
System.out.printf("%c: %d%n", vowels.charAt(i), counters[i]);
}