简体   繁体   中英

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!

You wont be able to do that in console:
as an alternative you can print values from each stack and then moving down like:

System.out.println("|"+stack1.pop()+"|\t|"+stack2.pop()+"|\t|"+stack3.pop()+"|\t|"+stack4.pop()+"|" );

Edit as commented - you can use String.format(...) , check here for formatting options available

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

How about this :

    ArrayList<Stack<Integer>> arrays=new ArrayList<Stack<Integer>>();
    arrays.add(stack1);
    arrays.add(stack2);
    arrays.add(stack3);
    arrays.add(stack4);

//Put some code here to  Determine the stack size, if all are unequal in size   
    int size=stack1.size(); 


    for(int i=0;i<size;i++){
        String value="";
        String temp="";

//4 = if you know the number of stacks is going to be 4 only

        for(int j=0;j<4;j++){ 

            //Handle here Empty Stack Exception and print blank
            value="|"+(String)(arrays.get(j)).pop().toString()+"|"+" ";
            temp=temp+value;


        }

        System.out.println(temp);



    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM