Упражнение с циклом: печать дерева на консоли с использованием циклов (застрял на деталях) - PullRequest
0 голосов
/ 13 ноября 2018

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

Цель: Пользователь вводит высоту дерева. Он печатается в следующем формате:

Eg высота 4

4|  *  |5=2+1+2   (width = 2 spaces+ 1 char + 2 spaces)
3| *** |5=1+3+1
2|*****|5=0+5+0
1| *** |5=1+3+1

Примечание. Корень всегда имеет длину 3 символа и должен составлять 1/4 высоты (округление)

Вот моя проблема: он отлично работает для каждого входа <8. Сначала я смотрел не туда, потому что чувствую, что это как-то связано с самим номером. Но 8 - первая высота, где корень - 2 строки вместо одной. (8 * 1/4 = 2) Несмотря на это, я не мог найти решение (даже плохое). </p>

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

Мое задание в основном выполнено, это лишь мелочь, которую я не могу понять. Не то чтобы я просил кого-нибудь сделать за меня домашнее задание; есть на обучение в этом я согласен.


Вот мой вывод для высоты (работает нормально)

 7|     *     |11=5+1+5
 6|    ***    |11=4+3+4
 5|   *****   |11=3+5+3
 4|  *******  |11=2+7+2
 3| ********* |11=1+9+1
 2|***********|11=0+11+0
 1|    ***    |11=4+3+4

Для чего-то большего, чем 8, например, 8 я получаю следующую проблему в корневых линиях дерева:

 8|      *      |11=5+1+5
 7|     ***     |11=4+3+4
 6|    *****    |11=3+5+3
 5|   *******   |11=2+7+2
 4|  *********  |11=1+9+1
 3| *********** |11=0+11+0
 2|    ***    |11=4+3+4              <--- amount of spaces is still correct but my formating got butchered as you can see, line 3 no longer touches the edges (|), its shifted 
 1|    ***    |11=4+3+4              

Вот мой код:

import java.util.Scanner;

public class SchleifenTestat
{
    public static void main(String[] args)
    {
        Scanner read = new Scanner(System.in);

          System.out.print("Enter height:");
          int height= read.nextInt();

          int heightOutput= height;
          int root = (int)(height*0.25F);  
          int width= ((height- root) * 2) -1; //Amount of chars in the widest tree line
          int spaces = (width- 1); //Amount of spaces line 1
          int charCount = 1;
          int tree = (height- root); 



          for(int i = 0; i < tree; i++)   
          {
              if(heightOutput<10)
              {
                  System.out.print(" ");  //To stay in format with heights <9

              }

                System.out.print(heightOutput+"|");
                heightOutput--;

                      for(int j=0; j<= height- i -3 ;j++)
                      {
                          System.out.print(" ");

                      }
                      for(int k=0; k < i*2 + 1; k++ )
                      {
                        System.out.print("*");

                      }
                      for(int j=0; j<=(height- i - 3);j++)  //5 = 2 + * + 2
                      {
                          System.out.print(" ");
                      }

                      System.out.print("|" + width+ "=" + (spaces/2) + "+" + charCount+ "+" + (spaces/2));
                      System.out.println();

                      charCount+=2;
                      spaces -=2;
          }

          for(int i = heightOutput; heightOutput> 0; heightOutput--)
          {
              System.out.print(" " + heightOutput + "|");

              for(int j = 0; j<((width-3)/2);j++)
              {
                  System.out.print(" ");          //Spaces left side 
              }

              System.out.print("***");           //Root

              for(int j = 0; j<((width-3)/2);j++)
              {
                  System.out.print(" ");          //Spaces right side 
              }

              System.out.print("|" + width+ "=" + ((width-3 )/2) + "+" + "3" + "+" + ((width- 3)/2));
              System.out.println("");

          }

    }
}

1 Ответ

0 голосов
/ 13 ноября 2018

Здесь много чего происходит.Я взял на себя смелость рефакторинга вашей программы немного / много.Каждый раз, когда вы используете одно и то же выражение несколько раз, например (width-3) / 2, подумайте о том, что это значение означает для вас, и передайте его в переменную с именем.То же самое с линиями, которые вы используете несколько раз, например, ваши левая и правая границы и так далее.Если вы сделаете это, ваша программа должна стать меньше чисел и больше семантических конструкций со значением, которое вы можете понять.Это где я приехал и вуаля это работает.: D

import java.util.Scanner;

public class SchleifenTestat
{
    public static void main(String[] args)
    {
        Scanner read = new Scanner(System.in);

          System.out.print("Enter height:");
          int height= read.nextInt();

          int heightOutput= height;
          int root = (int)(height*0.25F);  
          int width= ((height- root) * 2) -1; //Amount of chars in the widest tree line
          int spaces = (width- 1); //Amount of spaces line 1
          int spacesOneSide = spaces / 2;
          int charCount = 1;
          int tree = (height- root); 



          for(int i = 0; i < tree; i++)   
          {
              printLeftBorder(heightOutput);
              heightOutput--;

              printLine(spacesOneSide, charCount);

              printRightBorder(width, charCount, spacesOneSide);

              charCount+=2;
              spacesOneSide--;
          }

          while(heightOutput> 0)
          {
              int freeSpacesEachSide = ((width-3) / 2);
              printLeftBorder(heightOutput);

              printLine(freeSpacesEachSide, 3);

              printRightBorder(width, 3, freeSpacesEachSide);
              heightOutput--;
          }

          read.close();
    }

    private static void printRightBorder(int width, int charCount, int spacesOneSide)
    {
        System.out.print("|" + width+ "=" + spacesOneSide + "+" + charCount+ "+" + spacesOneSide);
        System.out.println("");
    }

    private static void printLeftBorder(int number)
    {
        if(number<10)
        {
            System.out.print(" ");  //To stay in format with heights <9
        }
        System.out.print(number+"|");       
    }

    private static void printLine(int spacesOneSide, int charCount)
    {
        printString(" ", spacesOneSide);
        printString("*", charCount);
        printString(" ", spacesOneSide);
    }

    private static void printString(String string, int times)
    {
        for(int i = 0; i < times; i++)
        {
            System.out.print(string);
        }
    }
}

Ох и закрой свои сканеры.Если у вас есть какие-либо вопросы относительно моего ответа, не стесняйтесь спрашивать, медленный день:)

Happy Coding

...