onlyforthis
onlyforthis

Reputation: 446

How to draw squares in java and put values inside it?

I have a Java program that has a linked list. I want to draw squares in command line and put the values of the linked list inside it. The output should be like this:

-----------------
| 5 | 7 | 8 | 9 |
-----------------

The numbers are just examples to show. This is what i have done so far:

public void display()
    {
        Node<data> temp = ll.getHead();//ll is linked list
        for(int i=0;i<ll.size();i++)System.out.print("---------");
        System.out.println();
        for(int i=0;i<ll.size();i++)System.out.print("|       |");
        System.out.println();
        for(;temp!=null;temp = temp.next)System.out.print("|   "+temp.data.Value+"  |");
        System.out.println();
        for(int i=0;i<ll.size();i++)System.out.print("|       |");
        System.out.println();
        for(int i=0;ll.size();i++)System.out.print("---------");
        System.out.println();
 }   

There is two problems with this code: it is not efficient at all, and if the value is more than 9 the lines will shift and all the drawing will be missed up. Is there a better way to do what i want? I assume this code is clear and enough to show the problem. If not please tell me to make it better. Thanks.

Upvotes: 0

Views: 257

Answers (2)

syllabus
syllabus

Reputation: 581

you can use a StringBulder for the upper and lower lines because they are the same. and you can build all the lines in the same loop, so that can handle variable lengths for values:

StringBuilder line = new StringBuilder();
StringBuilder values = new StringBuilder();

for(;temp!=null;temp = temp.next) {

  String value =Integer.toString(temp.data.Value);

  line.append("-");
  values.append("|");

  for(int i=0; i<value.length(); i++) { line.append("-"); }
  values.append(value);
}

line.append("-");
values.append("|");

System.out.println(line.toString());
System.out.println(values.toString());
System.out.println(line.toString());

Upvotes: 1

mosemos
mosemos

Reputation: 111

it seems that the number of dashes above and below n numbers is equal to 4n + 1. So, as for the loops:

for(int i = 0; i < (4 * ll.size()) + 1; i++) System.out.print("-");
    System.out.println();

// same as yours
for(;temp!=null;temp = temp.next)System.out.print("|   "+temp.data.Value+"  |");
    System.out.println();

for(int i = 0; i < (4 * ll.size()) + 1; i++) System.out.print("-");

Hope this will do the trick

EDIT: if your data are not numbers, then you will need to have a consistent space filled by each data. Then you will count the number of dashes for each square and get the formula for it. Good luck

Upvotes: 0

Related Questions