英文:
printing out stack without []
问题
以下是您要求的代码部分的翻译结果:
private int numberOfDisks;
private int startPillar;
private int targetPillar;
private int extraPillar;
private Stack<Integer>[] pillars = new Stack[3];
private int steps;
public Hanoi(int n, int start, int target) {
numberOfDisks = n;
startPillar = start - 1;
targetPillar = target;
extraPillar = 6 - start - target;
steps = 0;
pillars[0] = new Stack<Integer>();
pillars[1] = new Stack<Integer>();
pillars[2] = new Stack<Integer>();
for (int i = n; i > 0; i--) {
pillars[startPillar].push(i);
}
printStep();
}
private void printStep() {
for (int i = 1; i < 4; i++) {
System.out.print("t" + steps + " Pillar" + i + ": ");
if (!pillars[i - 1].isEmpty()) {
boolean first = true;
for (Integer disk : pillars[i - 1]) {
if (!first) {
System.out.print(" ");
}
System.out.print(disk);
first = false;
}
}
System.out.println();
}
}
请注意,我对代码进行了必要的调整,以便输出与您所需的格式匹配。
英文:
When I print the stack I want it without [] braces.
What should I change in my code or how can I do it so the output looks like the one that I show below?
here is my output now
t0 Pillar1: [3, 2, 1]
t0 Pillar2: []
t0 Pillar3: []
I want it to be:
t0 Pillar1: 3 2 1
t0 Pillar2:
t0 Pillar3:
here is my code
private int numberOfDisks;
private int startPillar;
private int targetPillar;
private int extraPillar;
private Stack<Integer>[] pillars = new Stack[3];
private int steps;
public Hanoi(int n, int start, int target)
{
numberOfDisks = n;
startPillar = start-1;
targetPillar = target;
extraPillar = 6 - start - target;
steps = 0;
pillars[0] = new Stack<Integer>();
pillars[1] = new Stack<Integer>();
pillars[2] = new Stack<Integer>();
for(int i = n; i > 0; i--)
{
pillars[startPillar].push(i);
}
printStep();
}
private void printStep()
{
for(int i=1;i<4;i++)
{
System.out.println("t"+steps+" " + "Pillar" + (i) + ": " + pillars[i-1]);
}
}
答案1
得分: 1
IMO 最快的方法是先将其放入一个字符串中
String result = pillars[i-1];
result = result.replace("[", "").replace("]", "");
System.out.println("t" + steps + " " + "Pillar" + (i) + ": " + result);
英文:
IMO the quickest way would be to put it in a String first
String result = pillars[i-1];
result = result.replace ("[", "").replace("]", "");
System.out.println("t"+steps+" " + "Pillar" + (i) + ": " + result);
答案2
得分: 0
使用 Arrays.toString()
:
System.out.println(Arrays.toString(pillars.toArray()).replace("[","").replace("]",""));
英文:
Use Arrays.toString()
:
System.out.println(Arrays.toString(pillars.toArray()).replace("[","").replace("]",""));
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论