java - 为什么我的 HashMap 没有被填充

标签 java hashmap

我的代码用于查找 100 以内的整数的阶乘。我正在使用 BigInteger,但我的问题是我的 HashMap 没有被填充。

public class FCTRL2 {   
static Map<Integer,BigInteger> list = new HashMap<Integer,BigInteger>();

  public static void main(String[] args){
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        int numberOfInput=0;
        String input=null;
        try {
            numberOfInput = Integer.parseInt(in.readLine());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while(numberOfInput > 0){
            try {
                input = in.readLine();
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            BigInteger inputBig = new BigInteger(input);
            **System.out.println(factorial(inputBig));** prints correct factorial
        **System.out.println(list.get(factorial(inputBig).intValue()));** prints null
            numberOfInput--;
        }
  }

  public static BigInteger factorial(BigInteger input){
    if(list.containsKey(input.intValue()))
        return list.get(input.intValue());

    if(input.equals(new BigInteger("1")))
        return new BigInteger("1");
    BigInteger output;
    output = input.multiply(factorial(input.subtract(new BigInteger("1"))));
    list.put(input.intValue(), output);
    return output;
  }

}

最佳答案

替换

System.out.println(list.get(factorial(inputBig).intValue()));

System.out.println(list.get(inputBig.intValue()));

因为您要在此处插入要映射的值:list.put(input.intValue(), output);

关于java - 为什么我的 HashMap 没有被填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093987/

相关文章:

java - 如何在 spring-boot 1.4.3 中覆盖 spring-boot 应用程序属性

java - hibernate : invalid ORDER BY expression

java - Spring、MongoDB 和 upserts : works with one-by-one updates, 批量更新失败

java - 如何使用 hibernate 使用现有对象创建复合键对象

java - hashmap 中的 bucket 到底是什么?

java - 将 hashMap 存储在数组中

java - 在 netbeans 中正确打包可运行的 Jar 项目

Java:从 HashMap 读取可以改变其状态吗?

java - 在 Android 中迭代 HashMap 并替换值

java - Arraylist 值未出现在 HashMap 中