You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java链表实现斐波那契数列输出?代码报错求修正

Fixing Your Fibonacci LinkedList Java Code

Let's break down what's going wrong with your code and fix it step by step—since you're new to LinkedLists, I'll explain each change clearly so you understand how to use them properly.

First, Let's List the Key Issues in Your Original Code

  • Constructor Misuse: Your constructor takes a LinkedList parameter with the same name as your class, which is confusing, and you don't actually need to pass a list in—this class should handle creating and populating the Fibonacci list itself.
  • Sum Method Doesn't Populate the List: You're calculating Fibonacci numbers in the sum() method, but you never add any of those numbers to fibonacciList—so the list stays empty forever.
  • Main Method Error: You created a raw LinkedList object and tried to call display() on it, but LinkedList doesn't have a display() method. That method belongs to your FibonacciLinkList class, so you need to create an instance of your class instead.
  • Missing Generics: You're using raw LinkedList types, which causes compile warnings and isn't good practice in Java.

Here's the Fixed Code

import java.util.LinkedList;

public class FibonacciLinkList {
    // Generic LinkedList to hold Integer values
    private LinkedList<Integer> fibonacciList;

    // Constructor: Initialize the LinkedList when creating an instance
    public FibonacciLinkList() {
        this.fibonacciList = new LinkedList<>();
    }

    // Populate the LinkedList with 20 Fibonacci numbers
    public void generateFibonacci() {
        // Start with the first two Fibonacci numbers: 0 and 1
        int a = 0;
        int b = 1;
        // Add the first number to the list
        fibonacciList.add(a);
        // If we need 20 numbers, loop 19 more times (since we already added one)
        for (int i = 1; i < 20; i++) {
            fibonacciList.add(b);
            // Calculate next number
            int next = a + b;
            a = b;
            b = next;
        }
    }

    // Display the contents of the LinkedList
    public void display() {
        System.out.println("20 Fibonacci Numbers:");
        System.out.println(fibonacciList);
    }

    public static void main(String[] args) {
        // Create an instance of YOUR FibonacciLinkList class
        FibonacciLinkList fibGenerator = new FibonacciLinkList();
        // Generate the Fibonacci numbers first
        fibGenerator.generateFibonacci();
        // Now display the populated list
        fibGenerator.display();
    }
}

Let's Explain the Changes

  1. Constructor Overhaul: We replaced the confusing parameterized constructor with a no-arg constructor that initializes fibonacciList directly. This way, every time you create a FibonacciLinkList instance, it starts with a fresh empty LinkedList ready to be populated.
  2. Renamed & Fixed the Generation Method: I renamed sum() to generateFibonacci() (more descriptive of what it does). Now, this method actually adds each calculated Fibonacci number to the list using fibonacciList.add(), which is how you add elements to a LinkedList in Java.
  3. Fixed Main Method Flow:
    • We create an instance of FibonacciLinkList (not a raw LinkedList)
    • We call generateFibonacci() first to fill the list with numbers
    • Then we call display() on our instance to print the list
  4. Proper Generics: We use LinkedList<Integer> everywhere to specify that this list holds integer values, avoiding raw type warnings.
  5. Corrected Fibonacci Logic: The initial values and loop count are adjusted to make sure we generate exactly 20 numbers starting from 0 (the standard Fibonacci sequence).

When you run this code, you'll see the full list of 20 Fibonacci numbers printed to the console!

内容的提问来源于stack exchange,提问作者David Gardener

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:16:11