Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format java string to look a specific way

I am new to Java and I have 4 int stacks that I need to print out in a specific way. The IDE I am using is BlueJ.

I want to print the arrays to look like the following

 |110|   |231|   |333|   |444|
 |111|   |232|   |334|   |447|
 |112|   |233|   |335|   |448|
 |113|   |234|   |336|   |449|
 |114|   |235|   |337|   |450|
 |115|   |236|   |338|   |451|

I am trying to this with System.out.println("|"+stack1.pop()+"|") but it creates a problem because I am not sure how to go back from the bottom, back to the top. Ex. 115 --> back up to 231. Each column represents a stack.

Thank you!

like image 343
Alex G Avatar asked Jul 30 '26 18:07

Alex G


1 Answers

Use String.format() better than concatenating a bunch of strings

System.out.println(String.format("|%s|\t|%s|\t|%s|\t|%s|",
                            stack1.pop(),stack2.pop(),stack3.pop(),stack4.pop()));

If you want to print the Stack elements in the opposite order, just reverse the stack first

like image 118
iTech Avatar answered Aug 02 '26 09:08

iTech