[英]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. 我是Java的新手,我有4个int堆栈,我需要以特定的方式打印出来。 The IDE I am using is BlueJ. 我使用的IDE是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. 我正在尝试使用System.out.println("|"+stack1.pop()+"|")
但它会产生问题,因为我不知道如何从底部返回,返回顶部。 Ex. 防爆。 115 --> back up to 231. Each column represents a stack. 115 - >返回到231.每列代表一个堆栈。
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 编辑为已注释 - 您可以使用String.format(...) , 在此处选中可用的格式选项
Use String.format()
better than concatenating a bunch of strings 使用String.format()
比连接一串字符串更好
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 如果要以相反的顺序打印Stack
元素,只需先reverse
堆栈
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 // 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.