簡體   English   中英

格式化java字符串以查找特定方式

[英]Format java string to look a specific way

我是Java的新手,我有4個int堆棧,我需要以特定的方式打印出來。 我使用的IDE是BlueJ。

我想打印數組看起來如下所示

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

我正在嘗試使用System.out.println("|"+stack1.pop()+"|")但它會產生問題,因為我不知道如何從底部返回,返回頂部。 防爆。 115 - >返回到231.每列代表一個堆棧。

謝謝!

您無法在控制台中執行此操作:
作為替代方案,您可以從每個堆棧打印值,然后向下移動,如:

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

編輯為已注釋 - 您可以使用String.format(...)在此處選中可用的格式選項

使用String.format()比連接一串字符串更好

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

如果要以相反的順序打印Stack元素,只需先reverse堆棧

這個怎么樣 :

    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 =如果您知道堆棧的數量將僅為4

        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);



    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM