Java 方法不';t正确地增加映射集的值

Java 方法不';t正确地增加映射集的值,java,map,hashset,Java,Map,Hashset,我的方法仍然在地图集中生成错误的值。其思想是将每个键的(char)值增加输入流吐出字符的次数。如果该键不存在,则会将其添加到地图集中并设置为1 public static Map<Character, Integer> getCounts(FileInputStream input) throws IOException{ Integer plusOne = 1; Map<Character, Integer> charCount = new HashM

我的方法仍然在地图集中生成错误的值。其思想是将每个键的(char)值增加输入流吐出字符的次数。如果该键不存在,则会将其添加到地图集中并设置为1

public static Map<Character, Integer> getCounts(FileInputStream input) throws IOException{ 
    Integer plusOne = 1;
    Map<Character, Integer> charCount = new HashMap<Character, Integer>();

    while(input.read() >= 0){
        Character aByte = (char) input.read();
              if(charCount.containsKey(aByte)){
        System.out.println(aByte);
        charCount.put(aByte, charCount.get(aByte)+plusOne);
            }
        else
        charCount.put(aByte, 1);
        }
        return charCount;    
}
你知道我的代码哪里有问题吗


Nick-

通过调用while循环的guard子句中的
input.read()
,您将丢弃一半的输入流:调用消耗一个字符。你必须记住这样的角色:

int b;
while( (b= input.read()) >= 0) {
  Character aByte = (char) b;
  ...
}

在while循环中有一个调用input.read()方法,另一个调用从流中获取字符,这反过来每次跳过一个字符

所以要解决这个问题,你可以使用

int intInput=0;
而((intInput=input.read())>=0){
字符aByte=(字符)输入;
您的代码原样。。。。
}

您尝试过使用调试器吗?是的,设置与每个键关联的值仍然有问题。。我找不到任何其他方法可供使用,并且基于Map api,这里似乎没有任何错误。调试器,当您检查
put()
调用的参数值时,您看到了什么?
int b;
while( (b= input.read()) >= 0) {
  Character aByte = (char) b;
  ...
}