我正在处理一项任务,我正在尝试将一个元素添加到 LinkedList。第一个代码块已给出,不应更改。第二个block是按照教授给我们的UML写的,位于另外一个类中。
import java.io.*;
import java.util.LinkedList;
public class Assignment10
{
public static void main(String[] args)
{
char input1;
String inputInfo = new String();
int operation2;
String line = new String();
//create a linked list to be used in this method.
LinkedList list1 = new LinkedList();
try
{
// print out the menu
printMenu();
// create a BufferedReader object to read input from a keyboard
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader (isr);
do
{
System.out.print("What action would you like to perform?\n");
line = stdin.readLine().trim(); //read a line
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
if (line.length() == 1) // check if a user entered only one character
{
switch (input1)
{
case 'A': //Add String
System.out.print("Please enter a string to add:\n");
String str1 = stdin.readLine().trim();
System.out.print("Please enter an index to add:\n");
inputInfo = stdin.readLine().trim();
int addIndex = Integer.parseInt(inputInfo);
list1.addElement(addIndex, str1);
break;
public void addElement(int index, Object element)
{
if(index < 0)
{
IndexOutOfBoundsException ex = new IndexOutOfBoundsException();
throw ex;
}
LinkedListIterator iterator = new LinkedListIterator();
for(int i = 0; i < index; i++)
{
if(iterator.hasNext()) // check if the iterator has a next value before
iterator.next(); // moving to next element
else
{
NoSuchElementException exception = new NoSuchElementException();
throw exception;
}
}
iterator.add(element);
} // end of addElement
这是 Eclipse 告诉我的:线程“main”java.lang.Error 中的异常:未解决的编译问题:方法 addElement(int, String) 未定义类型 LinkedList。
同样,我不应该更改第一个代码块,所以我的 addElement 方法一定有问题。有任何想法吗?抱歉,这是不可编译的,但我认为这实际上更像是一个概念性问题。