我对编程颇为陌生,因为这是我在大学的第一个学期,没有任何先验知识。现在在Python工作后,我们正在开发一个算命程序。我遇到的主要问题是试图返回交换机,询问用户是否想再次玩游戏,或者如果他们输入了8个案例之外的无效回复。还必须有一个嵌套在另一个while循环中的while循环。在循环切换case和嵌套while循环时遇到问题
Scanner user = new Scanner(System.in);
System.out.println("Welcome to the Fortune Telling program.\n"); //Welcome message
System.out.print("Would you like me to tell your fortune? Type 1 for yes and any other number for no: "); //ask for yes or no to run
int Var0 = user.nextInt();
if (Var0 == 1)
{
System.out.print("Enter a number 1-8 and I will tell your fortune: "); //ask for number between 1-8 to find fortune or invalid
int Var1 = user.nextInt();
switch (Var1)
{
case 1: //case 1-8 fortunes
System.out.println("\nYou will become great if you believe in yourself.");
break;
case 2:
System.out.println("\nSerious trouble with bypass you.");
break;
case 3:
System.out.println("\nYou will travel to many exotic places in your lifetime.");
break;
case 4:
System.out.println("\nYour ability for accomplishment will follow with success.");
break;
case 5:
System.out.println("\nWhen fear hurts you, conquer it and defeat it!");
break;
case 6:
System.out.println("\nYou will be called in to fulfill a position of higher honor and responsibility.");
break;
case 7:
System.out.println("\nYour golden opportunity is coming shortly.");
break;
case 8:
System.out.println("\nIntegrity is doing the right thing, even when nobody is watching.");
break;
default:
System.out.print("That's not a valid number. Try again.\n"); //invalid number try to rerun for correct response
}
} //display next print only on case not default
System.out.print("Would you like another fortune? Type 1 for yes and any other number for no: "); //loop this back into 'switch'
int Var2= user.nextInt();
System.out.print("Thank you for trying the fortune telling program."); //Thank you message
user.close();
}
}
为什么你需要一个嵌套的while循环? – Chiseled 2014-10-28 21:58:51
它是作业的一部分。但我不明白应该放在哪里,以便用户可以根据需要再次运行交换机。 @ Moh123 – 2014-10-28 22:03:20
你的任务可能是由不擅长编程的人设定的。恕我直言,你应该使用for循环,而不是while循环,因为你有一个迭代的方面(重新询问用户是否输入了无效的响应)。另外,这个任务不应该指定一个实现 - 选择一个是学习的一部分。 – Bohemian 2014-10-28 22:22:46