Domanda

Ho fatto una custom elenco collegato di nodo e di classi per la scuola e ho deciso di pratica come utilizzare facendo un testo-twist come gioco

Nella mia lista collegata classe, ho una traversa metodo che stampa la parola e per quanto tempo la parola è nella console.

Il codice che ho finora è questo:

MyLinkedList.java

package game;

public class MyLinkedList {
    public int counter;
    public MyNode head;
    public MyNode tail;

    public MyLinkedList() {
        counter = 0;
    }

    public void InsertToHead(MyNode m) {
        if (counter == 0) {
            head = tail = m;
        } else {
            m.setNext(head);
            head.setPrev(m);
            head = m;
        }
        counter++;
    }

    public int size() {
        return counter;
    }

    public boolean isEmpty() {
        if (counter == 0) {
            return true;
        } else {
            return false;
        }
    }

    public MyNode retrieveWord(String s) {
        MyNode n = head;
        while (n.next != null) {
            if (s.equals(n.getWord())) {
                return n;
            } else {
                n = n.next;
            }
        }
        if (s.equals(tail.getWord())) {
            return tail;
        }
        return null;
    }

    public MyNode retrieveLength(int l) {
        MyNode n = head;
        while (n.next != null) {
            if (l == n.getLength()) {
                return n;
            } else {
                n = n.next;
            }
        }
        if (l == tail.getLength()) {
            return tail;
        }
        return null;
    }

    public void traverse() {
        MyNode n = head;
        if (head != null) {
            while (n.next != null) {
                System.out.println(n.getWord() + "\t" + n.getLength());
                n = n.next;
            }
            System.out.println(tail.getWord() + "\t" + n.getLength());
        }
    }
}

MyNode.java

package game;

public class MyNode {

    public String word;
    public int length;
    public MyNode next, previous;

    public MyNode() {
        word = null;
        length = 0;
        next = null;
        previous = null;
    }

    public MyNode(String w, int l) {
        word = w;
        length = l;
        next = null;
        previous = null;
    }

    public void setNext(MyNode n) {
        next = n;
    }

    public void setPrev(MyNode n) {
        previous = n;
    }

    public void toHead(MyNode n){
        while(n.previous != null){
            n.setPrev(n);
        }
    }
    public void setWord(String w){
        word = w;
    }
    public String getWord(){
        return word;    
    }
    public void setLength(int l){
        length = l;
    }
    public int getLength(){
        return length;
    }
    public boolean hasNext(){
        return next != null;
    }
}

WordSort.java

package game;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class WordSort {
Scanner wordScan;

public WordSort() {
    MyLinkedList sixLetters = new MyLinkedList();
    MyLinkedList fiveLetters = new MyLinkedList();
    MyLinkedList fourLetters = new MyLinkedList();
    MyLinkedList threeLetters = new MyLinkedList();
    MyLinkedList rejects = new MyLinkedList();
    try {
        wordScan = new Scanner(new File("corncob_lowercase.txt"));
        wordScan.useDelimiter("\r\n");
        MyLinkedList ll = new MyLinkedList();
        while (wordScan.hasNext()) {
            String temp = wordScan.next();
            MyNode node = new MyNode();
            node.setWord(temp);
            node.setLength(temp.length());
            ll.InsertToHead(node);
            if (temp.length() == 6) {
                sixLetters.InsertToHead(node);
            } else if (temp.length() == 5) {
                fiveLetters.InsertToHead(node);
            } else if (temp.length() == 4) {
                fourLetters.InsertToHead(node);
            } else if (temp.length() == 3) {
                threeLetters.InsertToHead(node);
            } else {
                rejects.InsertToHead(node);
            }
        }
        wordScan.close();
        threeLetters.traverse();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.out.println("Missing File: corncob_lowercase.txt");
    }
}
}

e, infine, Driver.java

package game;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Driver extends JPanel {
private static final long serialVersionUID = 1L;

public Driver() {
    new WordSort();
}

public static void main(String[] args) {
    JFrame frame = new JFrame("Hidden Word");
    frame.setSize(500, 500);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Driver());
    frame.setVisible(true);
}
}

Ogni volta che eseguo questo codice, tutte le liste collegate (threeLetters, fourLetters, fiveLetters, e sixLetters) sono completamente bene fino alla fine, quando threeLetters.traverse() è chiamato, ottengo questo output (solo la parte finale)

act 3
ace 3
aby 3
abe 3
abducts 7
abductors   9
abductor    8
abductions  10
abduction   9
abducting   9
abducted    8
abdominal   9
abdomens    8
abdomen 7
abdication  10
abdicating  10
abdicates   9
abdicated   9
abdicate    8
abbreviations   13
abbreviation    12
abbreviating    12
abbreviates 11
abbreviated 11
abbreviate  10
abattoirs   9
abattoir    8
abatement   9
abashed 7
abasement   9
abandons    8
abandonment 11
abandoned   9
abandon 7
abalone 7
aardwolf    8
abe 8

Io non riesco a trovare il motivo per cui è che si verificano, ma sembra che la stampa di tutto quello che viene dopo abe e stampa abe due volte, una volta con la registrazione di 3 lettere e una volta come 8 lettere lungo!

Ho ottenuto il file di testo da questo sito:

http://www.mieliestronk.com/corncob_lowercase.txt

È stato utile?

Soluzione

Il problema qui è principalmente quello di design.Il difetto principale:il tentativo di utilizzare un'istanza MyNode in più liste collegate.

Quando si InsertToHead(node) si sta modificando il contenuto di node di per sé, in particolare la testa e avanti riferimenti.

Fix:Semplice dichiarare una new MyNode per ogni LinkedList che si desidera utilizzare.Nel progetto in particolare si stanno utilizzando due per ogni nodo. ll e uno dei <inset_number>Letters le liste.Quindi, dichiarare una nuova MyNode per ogni lista:

...
while (wordScan.hasNext()) {
    String temp = wordScan.next();
    MyNode node = new MyNode();
    MyNode node2 = new MyNode();
    node.setWord(temp);
    node2.setWord(temp);
    node.setLength(temp.length());
    node2.setLength(temp.length());
    ll.InsertToHead(node2);
...

Che dovrebbe risolvere il tuo problema.

Se volete sapere PERCHÉ stava accadendo.Traccia il codice.Ha a che fare con il tentativo di aggiungere nodi che hanno già dei più nodi collegati in un elenco.

Note Aggiuntive:

  • Fate del vostro meglio per evitare di public campi a meno che non sei SICURO che si desidera.I. E.in MyLinkedList qualcuno che utilizza la classe non dovrebbe essere in grado di accedere (o anche vedere!) il counter, head o tail, così quelli che dovrebbero essere fatte private.Se davvero si desidera accedere, creare get e set metodi

  • Nidificata se in blocco WordSort è un luogo perfetto per una interruttore come questa:

        switch(temp.length()) {
        case 6:
            sixLetters.InsertToHead(node);
            break;
        case 5:
            fiveLetters.InsertToHead(node);
            break;
        case 4:
            fourLetters.InsertToHead(node);
            break;
        case 3:
            threeLetters.InsertToHead(node);
            break;
        default:
            rejects.InsertToHead(node);
            break;              
        }
    
  • MyNode funziona bene come una classe separata.Però non ho molte volte si sceglie di implementare una semplice classe, come un nodo come un classe nidificata.Si può fare per alcuni molto la pulizia del codice.Provalo!

  • Prestare attenzione durante la progettazione le classi.Ci sono un sacco di metodi supplementare nel vostro disegno.Può essere facile per chug avanti la creazione di metodi che possono o non possono mai utilizzare.Mi piace creare solo metodi quando vedo che ho bisogno di loro in una classe che utilizza la classe in questione.

Codifica Felice!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top