gpt4 book ai didi

java - 使用HashTableMap计算第n个斐波那契数

转载 作者:行者123 更新时间:2023-12-02 11:21:21 26 4
gpt4 key购买 nike

我正在尝试实现 fibCalc2 方法来计算第 n 个斐波那契数,但我遇到了空指针异常,并且我不知道如何进一步进行。我的解决方案有意义吗?任何帮助将不胜感激。

注意:HashTableMap也是我自己实现的,所以和Java的实现有所不同。

更新:代码最后一行出现 NullPointerException

这是代码:

private static int callCount2;
private static Map<Integer, Long> ansMap = new LLQHashTableMap(10);



public static long fibCalc2(int n) {
if(n == 0 ||n == 1) return n;
if(ansMap.getSize() <= 2){
ansMap.define(0, (long) 0);
ansMap.define(1, (long) 1);
}
long tempVal1, tempVal2;
try {
long temp = ansMap.remove(n);
ansMap.define(n, temp);
} catch (Exception ex){

try {
long temp = ansMap.remove(n-1);
ansMap.define(n, temp);
tempVal1 = ansMap.getValue(n-1);
} catch (Exception ex1){
tempVal1 = fibCalc2(n-1);
}
try {
long temp = ansMap.remove(n-2);
ansMap.define(n, temp);
tempVal2 = ansMap.getValue(n-2);
} catch (Exception ex1){
tempVal2 = fibCalc2(n-2);
}
ansMap.define(n, tempVal1+tempVal2);
}
callCount2++;
return ansMap.getValue(n);
}

我的 map 界面:

package adt;

import impl.KeyValuePair;

/**
* A generic map
* @param <K>
* @param <V>
*/
public interface Map<K, V> {

/**
* Adds a new key-value mapping to the map, which will
* replace a previous key-value mapping that has the
* same key, if it exists
*
* @param key of the key-value pair to be added
* @param value of the key-value pair to be added
*/
public void define(K key, V value);

/**
* Returns the value associated with the given key
* in the map, if one exists, or null if the key is
* not in the map
*
* @param key whose value we want to return
* @return value associated with the given key
*/
public V getValue(K key);

/**
* Removes the key-value pair from the map that has
* the given key value, and returns the associated value
* if it exists; if the key is not in the map, the map
* remains unchanged, and null is returned
*
* @param key of the key-value pair that we want to remove
* @return value associated with the given key before removal
*/
public V remove(K key);

/**
* Removes and returns some key-value pair from the map,
* if the map is not empty; if the map is empty, an
* exception is thrown
*
* @return some key-value pair from the map
* @throws Exception if the map is empty
*/
public KeyValuePair<K, V> removeAny() throws Exception;

/**
* @return the number of key-value pairs in the map
*/
public int getSize();

/**
* Removes all key-value pairs from the map
*/
public void clear();

/**
* @return a String representation of the map
*/
@Override
public String toString();
}

最佳答案

NPE 上线

long temp = ansMap.remove(n);

当 n = 2 时,因为remove(n) 将返回 null,并且您不能将 null 分配给原始类型变量。

关于java - 使用HashTableMap计算第n个斐波那契数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896473/

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