0

我是 JAVA 新手,我正在尝试使用 java.util.LinkedList 库和动态数据类型(类)在 java 中实现一个简单的链接列表代码

代码如下 -

import java.util.LinkedList;
import java.util.Scanner;

//defining a custom data-type (class)
class LLObj{
static int NodeInt;
static char NodeChar;
LLObj(int x, char y){
    NodeInt = x;
    NodeChar = y;
    }
}

//main class    
public class LL2{

static int ChosenOption, TempInt, NodeCounter, TempCounter;
static char TempChar;

//creating scanner object
static Scanner ScannerObj = new Scanner(System.in);

//creating a link list
static LinkedList<LLObj> list = new LinkedList<>();

//main function
public static void main(String[] args){

    NodeCounter = 0;

    //driving menu
    for(;;){
    System.out.println("Enter 1 to add a node to linked list");
    System.out.println("Enter 2 to print the current list");
    ChosenOption = ScannerObj.nextInt();
    if(ChosenOption == 1){
        AddNew();
        }
    else if(ChosenOption == 2){
        PrintList();
        }
    else{
        System.out.println("Wrong Input. Try again!");
        }
    }
}

//AddNew function
public static void AddNew(){

    //getting input
    System.out.println("Enter integer");
    TempInt = ScannerObj.nextInt();
    System.out.println("Enter character");
    TempChar = ScannerObj.next().charAt(0);

    //Making a temperory node
    LLObj temp = new LLObj(TempInt,TempChar);

    //adding node to the list
    list.addLast(temp);
    }

public static void PrintList(){
    TempCounter = 0;
    while(TempCounter < NodeCounter){
        System.out.println(list[TempCounter].NodeInt);
        System.out.println(list[TempCounter].NodeChar);
        System.out.println("");
        TempCounter++;
        }
    }       
}

编译时收到的错误是 - “需要数组,但找到了 LinkedList”

请帮助我 1. 理解为什么会产生这个错误 2. 消除这个错误

任何帮助将不胜感激 :)

4

2 回答 2

3

ALinkedList没有[]运算符:

System.out.println(list[TempCounter].NodeInt);
                     //^^incorrect^^

使用LinkedList.get(int index)增强for循环遍历list.

于 2013-03-27T08:39:54.977 回答
2

list.get(TempCounter).NodeInt改为使用

于 2013-03-27T08:57:35.667 回答