я понял что ошибка в методе ToString. Именно при рекурсивном выводе строка обновляется, как мне ее исправить? public class Node { int x; Node l, r; public Node() {} public Node(int x){ this.x = x; } public void add(int x){ //Добавление элемента в дерево if(this == null){ // ТУТ ОШИБКА this.x = x; // Если дерево пусто то создаем его } if(x < this.x){ // Если добавляемое значение меньше значения узла if(l != null) l.add(x); // Если узел не пуст вызываем рекурсивно else{ l = new Node(x); // Если нашли пустое место создаем узел } } if(x > this.x){ // Если добавляемое значение больше значения узла if(r != null) r.add(x);// Если узел не пуст вызываем рекурсивно else{ r = new Node(x); // Если нашли пустое место создаем узел } } } public String toString() { String s= null; if(this != null) { // ТУТ ОШИБКА l.toString(); s += this.x + " "; r.toString(); } return s; } } Maine
public static void main(String[] args) { Random r = new Random(); Node Tree = new Node(); for (int i = 0; i < 5; i++) { Tree.add(r.nextInt(100)); } System.out.println(Tree.toString()); } please tell me throws an error
Exception in thread "main" java.lang.NullPointerException at Node.toString(Node.java:31) at Start.main(Start.java:13) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
thisbenull? This error report does not correspond to the given source code. Maybe something was not compiled there and a completely different version works? The error should be on the strings += this.x...because s = null at the very beginning and before it changes. Or just someone can not count the lines? - Sergeythis == nullchecks, inside the non-static method ofthisby definition, cannot benull(and inside a static compiler will not allow you to refer tothisin this context). Do you understand thatthisis a link to the current instance of a class (when you work inside non-static class methods, then you are by definition working with a specific instance of a class)? - StateItPrimitivel,r- Grundy are initializedmainmethod code - Grundy