Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> не правильные значения при выводе на экран 
:(
    Опции темы
ArniLand
Дата 28.9.2010, 20:09 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 227
Регистрация: 17.8.2008

Репутация: нет
Всего: нет



Хочу вывести на экран вывести все значения переменных data, name, surname, course, ticket, day, month, year, то есть вывести нужно информацию о трех разных студентах но выводиться бред. Пишу в NetBeans. Вот результат выполнения программы 
Цитата
run:
data: 2
name: 4534
BUILD SUCCESSFUL (total time: 1 second)

Какое то странное значение переменной name, и остальные переменные не выводиться. Помогите решить проблему пожалуйста.

Код программы:
Код

package tree_final;
public class BinaryTree {
    private  Node root;
    public BinaryTree()

    {  root = null;  }

    private void PrintRec(Node root){
    if(root != null)
        return;
    root.Print();
      System.out.println();
    PrintRec(root.left);
    PrintRec(root.right);
    }
    public void Print(){
    PrintRec(root);
    return;
    }
    public void insert(int data, String name, String surname,
            String course, String ticket, int day, int month, int year ){

        Node n = new Node(data, name, surname, course, ticket, day, month, year);
        if (root == null){
            root = n;
        }
        else {
         Node current = root;
         Node parent;
         while(true) {
             parent = current;
             if(data < current.data){
                 current = current.left;
                }
                if (current == null) {
                    parent.left = n;
                    return;
                }
          else {
                current = current.right;
                if(current == null){
                    parent.right = n;
                    return;

                }
              }
           }
       }
    }



       public Node find(int key){
       Node current = root;

       while(current.data != key){
           if(key < current.data){
               current = current.left;
           }
           else {
                current = current.right;
           }

           if(current == null) {
               return null;
           }

       }
       return current;
    }
      public void inorderPrint(Node root) {
          if (root == null) {
              inorderPrint(root.left);
              System.out.println(root.data + "");
              inorderPrint(root.right);

          }
      }

      public boolean delete(int key) {
          Node current = root;
          Node parent = root;
          boolean isLeft = true;




        if (current.course == "3" && (current.month>=6 && current.month<=8)) {
              while(current.data != key) {
                  parent = current;
                  if(key < current.data) {
                      isLeft = true;
                      current = current.left;
                  }
                  else {
                  if(current == null) {
                    return false;
                    }
                  }
              }

              if(current.left == null && current.right == null) {
                  if (current == root)
                      root = null;

                   else if(isLeft)
                     parent.left = null;
                    else
                      parent.right = null;

              }

               else if (current.right == null)
                  if( current == root)
                      root = current.left;
                  else if(isLeft)
                      parent.left = current.left;
                  else
                      parent.right = current.right;

              else if(current.left == null)
                  if(current == root)
                      root = current.right;
                  else if(isLeft)
                      parent.left = current.right;
                  else
                      parent.right = current.right;

              else {
                  Node successor = getSuccessor(current);

                  if(current == root)
                      root = successor;
                  else if(isLeft)
                      parent.left = successor;
                  else
                      parent.right = successor;

                  successor.left = current.left;

              }

          }

          return true;




      }

      private Node getSuccessor(Node delNode)
      {
      Node successorParent = delNode;
      Node successor = delNode;
      Node current = delNode.right;
      while(current != null)
         {
         successorParent = successor;
         successor = current;
         current = current.left;
         }

      if(successor != delNode.right)
         {
         successorParent.left = successor.right;
         successor.right = delNode.right;
         }
      return successor;
      }





    public static void main(String[] args ) {
        BinaryTree theTree = new BinaryTree();

        theTree.insert(1, "vasa", "pupkin", "3", "456987", 2, 7 , 1992);
        theTree.insert(2, "ivan", "ivanov", "2", "789898", 3, 5 , 1991 );
        theTree.insert(4, "dima", "vengel", "3", "7896546", 9, 4, 1992);
        theTree.Print();
        theTree.Print();
        theTree.Print();


 }
}
class Node {
        Node left;
        Node right;
        int data;
        String name;
        String surname;
        String course;
        String ticket;
        int day;
        int month;
        int year;
        public Node(int data, String name, String surname, String course, String ticket, int day, int month, int year){
            this.data = data;
            this.name = name;
            this.surname = surname;
            this.course = course;
            this.ticket = ticket;
            this.day = day;
            this.month = month;
            this.year = year;
        }
      public void Print(){
System.out.println("data" + data);
System.out.println("Имя" + name);
System.out.println("Фамилия" + surname);
System.out.println("Курс" + course);
System.out.println("День" + day);
System.out.println("месяц" + month);
System.out.println("год" + year);
}
}


Это сообщение отредактировал(а) ArniLand - 28.9.2010, 20:10
PM MAIL   Вверх
vatuska
Дата 28.9.2010, 20:21 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 27
Регистрация: 19.9.2010

Репутация: нет
Всего: нет



попробуй вызовы insert  написать так:
theTree.insert(1, new String("vasa"), new String("pupkin"), new String("3"), new String("456987"), 2, 7 , 1992);
не понимаю, зачем номер курса делать строкой, для этого целого числа вполне должно хватать, а метод Print() Нужно только один раз вызывать, он всё дерево выводит слева-направо

PM MAIL ICQ   Вверх
jk1
Дата 28.9.2010, 20:23 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
***


Профиль
Группа: Участник
Сообщений: 1168
Регистрация: 17.10.2008
Где: Санкт-Петербург

Репутация: 40
Всего: 75



Правильный вариант
Код

    private void PrintRec(Node root) {
        if (root == null)
            return;
        root.Print();
        System.out.println();
        PrintRec(root.left);
        PrintRec(root.right);
    }

Ошибка в том, что у вас стояло != в условии выхода и соответственно ничего не выводилось когда данные на самом деле были.


--------------------
Opinions are like assholes — everybody has one
PM MAIL   Вверх
ArniLand
Дата 28.9.2010, 22:18 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 227
Регистрация: 17.8.2008

Репутация: нет
Всего: нет



Спасибо за помощь.
1 Вот подправленный код, добавлен метод вывода последовательного обхода. Но результат обхода(какое дерево стало после обхода) не вводиться, а выводиться просто надпись о предварительном. Как это исправить?
2. И подскажите как сделать, чтобы выводились узлы после удаления узлов согласно условию?

Код


package tree_final;
public class BinaryTree {
    private  Node root;
    public BinaryTree()

    {  root = null;  }

     private void PrintRec(Node root) {
        if (root == null)
            return;
        root.Print();
        System.out.println();
        PrintRec(root.left);
        PrintRec(root.right);
    }
    public void Print(){
    PrintRec(root);
    return;
    }
    public void insert(int data, String name, String surname,
            String course, String ticket, int day, int month, int year ){

        Node n = new Node(data, name, surname, course, ticket, day, month, year);
        if (root == null){
            root = n;
        }
        else {
         Node current = root;
         Node parent;
         while(true) {
             parent = current;
             if(data < current.data){
                 current = current.left;
                }
                if (current == null) {
                    parent.left = n;
                    return;
                }
          else {
                current = current.right;
                if(current == null){
                    parent.right = n;
                    return;

                }
              }
           }
       }
    }



       public Node find(int key){
       Node current = root;

       while(current.data != key){
           if(key < current.data){
               current = current.left;
           }
           else {
                current = current.right;
           }

           if(current == null) {
               return null;
           }

       }
       return current;
    }
      public void inorderPrint(Node root) {
          if (root == null) {
              inorderPrint(root.left);
              System.out.println(root.data + "");
              inorderPrint(root.right);


          }
      }
      public void travers(){
          System.out.println("Inorder traversal");
          inorderPrint(root);
      }
      public boolean delete(int key) {
          Node current = root;
          Node parent = root;
          boolean isLeft = true;




        if (current.course == "3" && (current.month>=6 && current.month<=8)) {
              while(current.data != key) {
                  parent = current;
                  if(key < current.data) {
                      isLeft = true;
                      current = current.left;
                  }
                  else {
                  if(current == null) {
                    return false;
                    }
                  }
              }

              if(current.left == null && current.right == null) {
                  if (current == root)
                      root = null;

                   else if(isLeft)
                     parent.left = null;
                    else
                      parent.right = null;

              }

               else if (current.right == null)
                  if( current == root)
                      root = current.left;
                  else if(isLeft)
                      parent.left = current.left;
                  else
                      parent.right = current.right;

              else if(current.left == null)
                  if(current == root)
                      root = current.right;
                  else if(isLeft)
                      parent.left = current.right;
                  else
                      parent.right = current.right;

              else {
                  Node successor = getSuccessor(current);

                  if(current == root)
                      root = successor;
                  else if(isLeft)
                      parent.left = successor;
                  else
                      parent.right = successor;

                  successor.left = current.left;

              }

          }

          return true;




      }

      private Node getSuccessor(Node delNode)
      {
      Node successorParent = delNode;
      Node successor = delNode;
      Node current = delNode.right;
      while(current != null)
         {
         successorParent = successor;
         successor = current;
         current = current.left;
         }

      if(successor != delNode.right)
         {
         successorParent.left = successor.right;
         successor.right = delNode.right;
         }
      return successor;
      }





    public static void main(String[] args ) {
        BinaryTree theTree = new BinaryTree();

        theTree.insert(1, "vasa", "pupkin", "3", "456987", 2, 7 , 1992);
        theTree.insert(2, "igor", "melnik", "2", "4477", 7, 1 , 1992);
        theTree.insert(3, "dima", "ladov", "2", "787999", 9, 3 , 1991);
        theTree.insert(4, "igor", "melnik", "2", "4477", 3, 8 , 1992);
        theTree.Print();

        theTree.travers();

        
        
        


 }
}
class Node {
        Node left;
        Node right;
        int data;
        String name;
        String surname;
        String course;
        String ticket;
        int day;
        int month;
        int year;
        public Node(int data, String name, String surname, String course, String ticket, int day, int month, int year){
            this.data = data;
            this.name = name;
            this.surname = surname;
            this.course = course;
            this.ticket = ticket;
            this.day = day;
            this.month = month;
            this.year = year;
        }
      public void Print(){
System.out.println("data" + data);
System.out.println("Имя" + name);
System.out.println("Фамилия" + surname);
System.out.println("Курс" + course);
System.out.println("День" + day);
System.out.println("месяц" + month);
System.out.println("год" + year);
}
}




Это сообщение отредактировал(а) ArniLand - 28.9.2010, 22:19
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
javastic
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux, javastic.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Общие вопросы | Следующая тема »


 




[ Время генерации скрипта: 0.0508 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.