【发布时间】:2015-11-20 08:00:37
【问题描述】:
这是我的代码的要点和它的功能。这是一个选择你去哪里的游戏来选择你的路径。例如,如果您在开始时选择路径 a,则可以在路径 d 和 e 之间进行选择,如果您选择了 d,则可以移动到 f 和 g 等等。
我想添加回溯。例如,如果我一开始选择a,然后一直到f,我希望能够回到d,再次在f和g之间进行选择,或者一直回到起点并选择b.
我最初的想法是在我需要回溯时使用一些东西来告诉代码回到某一行代码,但据我了解,java 中没有 goto。我有使用循环的想法。 (我特别想 while 循环。)我不知道如何构造循环以回溯。
这是我的代码:
public class PathGame {
public static void main (String[] args) {
String name = JOptionPane.showInputDialog("Hello! Welcome to my paths! What is your name, adventurer?");
JOptionPane.showMessageDialog(null, "Well then " + name + ", here's how this works...some generic instructions");
String startingChoice = JOptionPane.showInputDialog("Choose your path, a, b, or c.");
if (startingChoice.equals("a")){
String aChoice = JOptionPane.showInputDialog("Choose path d or path e");
if (aChoice.equals("d")) {
String dExamineChoice = JOptionPane.showInputDialog("path f or g?");
if (dExamineChoice.equals("f")) {
JOptionPane.showMessageDialog(null, name + "...!");
}
else if (dExamineChoice.equals("g")) {
JOptionPane.showMessageDialog(null, "Stuff g");
}
}
else if (aChoice.equals("e")) {
JOptionPane.showMessageDialog(null, "Stuff e");
}
else if (aChoice.equals("goBack")) {
///Backtrack back to start
}
}
else if (startingChoice.equals("b")) {
String bChoice = JOptionPane.showInputDialog("Path h or i?");
if (bChoice.equals("h")) {
String hChoice = JOptionPane.showInputDialog("Path j, k, or l?");
if (hChoice.equals("j")) {
String jExamine = JOptionPane.showInputDialog("m or n?");
if (jExamine.equals("m")) {
JOptionPane.showMessageDialog(null,"Stuff m");
}
else if (jExamine.equals("n")) {
JOptionPane.showMessageDialog(null,"Stuff n");
}
}
else if (hChoice.equals("k")) {
JOptionPane.showMessageDialog(null,"Stuff k");
}
else if (hChoice.equals("l")) {
JOptionPane.showMessageDialog(null,"Stuff l");
}
}
else if (bChoice.equals("i")) {
JOptionPane.showMessageDialog(null,"Stuff i");
}
}
}
}
【问题讨论】:
-
您需要将可能的选择存储在图形数据结构中:从根节点开始,边到节点
a、b和c,从a那里是d和e等的边...然后用户选择只是此图中遍历节点的列表(即路径)。要返回,只需从列表中删除最后一个条目。 -
请原谅我,但我不熟悉那种图形数据结构。我该怎么做呢?我明白你在实际层面上所说的话,我只是不知道如何将其翻译成代码,如果这有意义的话。
标签: java loops if-statement nested-if