gpt4 book ai didi

java - 字符在 while 循环中不增加数组计数器?

转载 作者:行者123 更新时间:2023-11-30 07:31:07 26 4
gpt4 key购买 nike

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

}
}

当我运行文件时,只有当它应该检测到数百个 e 时,它​​才会检测到 3 个 e。我没有发现我的代码存在任何会导致问题的问题,请帮助。我假设它必须在我的分隔符和结束时间之间,因为其余部分不在书中。

最佳答案

您的分隔符没有按照您想象的方式工作。假设您打算从 inputFileName 读取数据,您可以构造一个 FileScanner 来执行此操作(记住关闭 Scannerfinally block 中,或者使用 try-with-resources statement )。您还可以通过元音元音的位置确定正确的计数器索引。最后,您可以使用格式化的 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]);
}

关于java - 字符在 while 循环中不增加数组计数器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122375/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com