2012-05-09 3 views
-1

ОК, так что поиск - это моя слабая область на Java и может действительно использовать помощь в отношении того, с чего начать на этом задании !! Элемент данных n больше не нужен. LinkedList должен быть создан и назначен для списка в конструкторе, а не в run(). makeScanner(), getPerson() и main() не должны быть изменены. Классы Person и FileFormatException также не должны быть изменены. display() больше не будет компилироваться, поскольку theList больше не является массивом. Вы можете либо изменить его, чтобы использовать foreach, либо просто удалить его. run() имеет цикл, который добавляет объекты Person в массив. Измените его так, чтобы он вместо этого добавлял их в список. Рассмотрим:Поиск Задача затруднения ... Связанный список

theList.add(p); 

Индекс переменных и n больше не нужны. Изменить поиск() для выполнения линейного поиска в списке, а не в массиве. Самый простой способ - использовать foreach и вернуть правильного Человека, если он найден. Если правильное Лицо не найдено, оно должно возвращать значение null, как и раньше.

Это то, что я до сих пор:

import java.util.LinkedList; 
import java.io.IOException; 
import java.net.URL; 
import java.util.Scanner; 


public class ContactList { 

private LinkedList<Person> theList; 

private int n;   // the number of Persons in theList 
private Scanner keyboard; 

public ContactList() { 
keyboard = new Scanner(System.in); 
} // no-arg constructor 

// Returns a Scanner associated with a specific text-based URL 
// online. 
private Scanner makeScanner() throws IOException { 
final String source = 
    "http://userpages.umbc.edu/~jmartens/courses/is247/hw/05/05.txt"; 
final URL src = new URL(source); 
return new Scanner(src.openStream()); 
} // makeScanner() 


// Return a Person instance based upon data read from the given 
// Scanner. 
private Person getPerson(final Scanner in) throws FileFormatException { 
if (!in.hasNextLine()) 
    return null; 

String line = in.nextLine().trim(); 
int key = Integer.parseInt(line); 
String name = in.nextLine().trim(); 
String mail = in.nextLine().trim().toLowerCase(); 
if (in.hasNextLine()) { 
    String empty = in.nextLine().trim(); // skip blank line 
    if (empty.length() > 0) 
    throw new FileFormatException("missing blank line"); 
} // if 

return new Person(key, name, mail); 
} // getPerson() 


// Display the array contents. 
private void display() { 
for (int i = 0; i < n; ++i) 
    System.out.println(theList[i]); 
} // display() 


// Read the Person objects from the web page and then start the user 
// interface. 
private void run() throws IOException { 
theList = new Person[1024]; 
try { 
    Scanner in = makeScanner(); 

    int index = 0; 
    Person p = getPerson(in); 
    while (p != null) { 
    theList[index++] = p; 
    p = getPerson(in); 
    } 
    n = index; 
} catch (IOException e) { 
    System.err.println("Error reading web page: " + e); 
    System.exit(1); 
    // The call to exit may be overkill, but it is nice to return an 
    // error (nonzero) value to the environment. Since main() does 
    // nothing after run() returns, simply returning to main() would 
    // be acceptable also. Perhaps the easiest way to do this is to 
    // simply move the call to ui() below into the try block. Then if 
    // an exception is thrown, the UI never executes. 
} // catch 

// Run the user interface. 
    ui(); 
// display(); 
} // run() 

// Loop prompting the user for an integer key. Terminate on a negative 
// key. If a record matching the key is found, display the 
// record. Otherwise, indicate that no matching record was found. 
private void ui() { 
int key = getKey(); 
while (key >= 0) { 
    Person p = search(key); 
    if (p == null) 
    System.out.println("No person matching key " 
         + key 
         + " found."); 
    else 
    System.out.println(p); 
    key = getKey(); 
} // while not done 
} // ui() 

private int getKey() { 
System.out.print("\nPlease enter a key: "); 
int key = keyboard.nextInt(); 
return key; 
} // getKey() 

private Person search(final int key) { 
for (int index = 0; index < n; ++index) 
    if (key == theList[index].getId()) // Is this the right one? 
    return theList[index]; 

return null;  // apparently the requested object is not present 
} // search() 

public static void main(String[] args) throws IOException { 
ContactList cl = new ContactList(); 
cl.run(); 
} // main() 

} // class ContactList 
+4

Вы понимаете концептуально, как работает LinkedList? Если нет, это хорошее место для начала. – Charles

+0

Что вы думаете? Действительно ли этот код необходим для конкретного вопроса? – amit

ответ

3

Первое, что я хотел бы сделать, это изменить список вашего заявления! (Как вы сказали)

изменение:

private Person[] theList; 

в

private LinkedList<Person> theList; 

Затем с помощью компилятора печатать все ваши ошибки компиляции или смотреть на все красные загогулины, произведенных в вашем язя.

В каждой точке, где есть ошибка компиляции или красная кривая, определите, какую операцию массива вы пытаетесь выполнить. Затем выполните поиск на этой странице для правильной работы или последовательности операций, которые эквивалентны. http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html

0

http://www.java2s.com/Code/Java/Collections-Data-Structure/Useforeachlooptogothroughelementsinalinkedlist.htm

Это пример использования для каждого оператора, чтобы связать с помощью простого списка. Вы должны изменить свое объявление из массива в связанный список и попробовать что-то похожее на значение для каждого в приведенном выше примере.

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html Дополнительная информация по теме, если вам нужно немного больше фона.

Смежные вопросы