【发布时间】:2019-09-14 09:53:13
【问题描述】:
我正在做河内塔的家庭作业。我试图将 i 变量每次增加 1,但它增加 2。此外, ("[g]et, [p]ut... 字符串被打印两次,而不是一次。发生了什么?!请帮忙!>
我尝试添加一个 i--;在 if (p) 上,但这不起作用。
import java.util.Scanner;
/**
* Simulates a tower that can hold disks.
* @author S. Camilleri
* @author <your name>
*/
public class TowersOfHanoi {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// This array holds the disks. A 0 represents no disk.
int[] tower = new int[5];
// This index represents the first available empty spot for a disk.
int index = 0;
int towerCounter = 0;
int length = tower.length;
boolean playing = true;
while (playing)
{
/********************
* Display the tower
********************/
System.out.println();
System.out.print("{ ");
while (towerCounter < length) {
tower[towerCounter] = 0;
System.out.print(tower[towerCounter]);
towerCounter = towerCounter + 1;
}
String choice;
int size;
for (int i=0; i<length; i++) {
/********************
* Get action from user
********************/
System.out.println();
System.out.println("[g]et, [p]ut or [e]xit?");
choice = input.nextLine();
// Get
if (choice.equals("g"))
{
tower[i] = 0;
System.out.println();
towerCounter = 0;
i--;
System.out.print("{ ");
while (towerCounter < length) {
System.out.print(tower[towerCounter]);
towerCounter = towerCounter + 1;
}
}
// Put
else if (choice.equals("p"))
{
System.out.println("Disk?");
size = input.nextInt();
tower[i] = size;
towerCounter = 0;
System.out.print("{ ");
while (towerCounter < length) {
System.out.print(tower[towerCounter]);
towerCounter = towerCounter + 1;
}
}
// Exit
else if (choice.equals("e"))
{
playing = false;
}
}
}
}
}
应答复者的要求,我发布了整个代码。
【问题讨论】:
-
你为什么要
i--? -
i应该算什么?为什么只在i计数到length之前一直询问用户输入? -
我想你可能需要告诉我们什么叫这个,如果有的话。
-
@DawoodibnKareem 我这样做了——试图让字符串不会重复。
-
@KevinAnderson 我正在计算塔上的磁盘数量。当塔填满时它会停止。