Ich versuche, meine BST in eine Textdatei zu schreiben, aber einige, wie es nicht funktioniert. Ich würde gerne wissen, wo ich versagt habe, denn ab sofort wird nichts mehr in die Datei geschrieben. Das Problem ist in der BinaryTree.java
. Die display()
Methode ist, wo ich versuche, die Elemente in Student.txt
Datei zu platzieren.Warum wird mein BST nicht in eine Datei geschrieben?
Hier ist mein Node.java
:
class Node {
Student data;
Faculty data2;
Node left;
Node right;
public Node(Student data) {
this.data = data;
this.left = left;
this.right = left;
}
public Node(Faculty data2) {
this.data2 = data2;
this.left = left;
this.right = right;
}
}
meine hier BinaryTree.java
:
int index = 0;
String[] sa = new String[index];
public void studentArray() {
studentArray(root,index);
}
public int studentArray(Node root, int index) {
if(root.left != null) {
index = studentArray(root.left, index);
}
sa[++index] = root.data.getLastName().toString();
if(root.right != null) {
index = studentArray(root.right,index);
}
return index;
}
public void displayStudent(Node root) throws IOException {
if(root != null) { // If root isn't empty.
if(root.left != null) {
displayStudent(root.left); // Recursively display left nodes.
}
System.out.println(root.data.toString()); // Print to the console data that's in the root in order.
if(root.right != null) {
displayStudent(root.right); // Recursively display right nodes.
}
}
String file = "Student.txt";
FileWriter fw = new FileWriter(new File(file));
try {
for(index = 0; index < sa.length; index++) {
fw.write(sa[index] + " ");
}
fw.close();
} catch(Exception e) {
System.out.println("File not found.");
}
}
meine hier Main.java
:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
Student student1 = new Student("Mike", "Piazza", "S3123456");
Student student2 = new Student("Jack", "Jill", "S3123456");
Student student3 = new Student("Alice", "Jones", "S3123456");
BinaryTree bt = new BinaryTree();
bt.insertStudent(student1);
bt.insertStudent(student2);
bt.insertStudent(student3);
bt.displayStudent(bt.root);
}
Hier ist meine Student.txt
Datei:
*displays nothing*
Danke für Ihre Antwort. Es ist sehr geschätzt: D! Können Sie bitte etwas mehr auf 'ArrayList' Teil erweitern? Insbesondere der 'sa.get (i)' -Teil und der 'for (s: sa) {' -Teil. Vielen Dank :). – bojack
Erweitert die Antwort –