【问题标题】:Method doesn't increment Values of Mapset properly方法没有正确增加 Mapset 的值
【发布时间】:2023-04-09 11:27:02
【问题描述】:

我的方法仍然在我的 MapSet 中产生错误的值。这个想法是通过输入流吐出字符的次数来增加每个键的(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;    
}

这是测试文件的组成:这是一堆文本。点击保存。点击保存..

这些是我的结果:{f=0, =2, c=0, C=1, .=2, k=1, h=0, i=2, ?=0, v=1, u =0, t=0, s=2, x=0}

这是我的测试代码:

public static void main(String[] args)throws FileNotFoundException, IOException {
    FileInputStream test = new FileInputStream(new File("BunchofText.txt"));
    System.out.println(HuffmanNode.getCounts(test));
}

我的代码有问题的任何想法?

尼克-

【问题讨论】:

  • 你试过使用调试器吗?
  • 是的,设置与每个键关联的值仍然有问题。我找不到任何其他方法可以使用,并且基于 Map api,它看起来没有任何问题这里
  • 在调试器中,当您检查 put() 调用的参数值时会看到什么?

标签: java map hashset


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    int intInput = 0; while( (intInput = input.read()) >=0 ){ Character aByte = (char)intInput; your code as it is .... }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2018-07-09
      相关资源
      最近更新 更多