Format java string to show specific path
I'm new to Java and I have 4 built-in stacks that I need to print in a specific way. The IDE I'm using is BlueJ.
I want to print arrays so they look like this
|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'm trying to do it with help System.out.println("|"+stack1.pop()+"|")
, but it creates a problem because I'm not sure how to go back, back. Ex. 115 -> back to 231. Each column represents a stack.
Thank!
+3
source to share
3 answers
You won't be able to do this in the console:
alternatively, you can print values from each stack and then move 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 available formatting options
+2
source to share
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 how many stacks there will be only 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);
}
0
source to share