为什么我的 do-while 循环在 java 中过早中断?



所以我的问题是,当它运行时,一旦你输入一个,它只会打印下一个开关并结束程序,而不允许输入下一个选择。这是我到目前为止所做的。

  1. 我花了 while(选择 == 1( 并将其放在案例 1 中。
  2. 我花了 while(选择 == 1(,只是将开关与 在开关中使用了继续语句。
  3. 当我取出最后两个休息时间时,我得到 无限循环。

关于我正在做什么的任何提示都会有所帮助。

package Spook;
import java.util.Scanner;
public class House {
Scanner in = new Scanner(System.in);
static void p(String I) {
System.out.println(I);
}
public void game() {
p("nWelcome To Spook House, were all Spooks will haunt you.");
do {
p("nPlease make your selection");
p("         1.  Enter House for some Scares.");
p("         2. Too Scared to Enter.");
p("         3. Really Scared Please let me exit.");
p("Choose one please.");
char choice = in.next().charAt(0);
switch (choice) {
case '1':
p("nAs prepare to enter the house, The door slowly creaks open.");
p("nYou enter the house and the door slams shut.");
p("What do you do????");
p("         1. Try to open the door.");
p("         2. Find the nearist closet and hide.");
p("         3. Continue onward.");
p("         4. Faint and end game.");
break;
case '2':
p("nWhat are you a chicken, Just press 1!!!!!");
break;
case '3':
p("nFine you win chicken, now ending.");
System.exit(0);
break;
}
while (choice == '1') {
switch (choice) {
case '1':
p("nAs you twist the door knoob and try to pull it open. You feel a gust of wind that pushes you down.");
break;
case '2':
p("nYou run towards the closet hoping to hide till daylight.");
p("You start to shake and laugh nerviously.");
break;
case '3':
p("nYou explore the first room.");
p("You see an old crooked picture of a scary clown.");
break;
case '4':
p("nYou have been easily to SPOOKED MMMMUUUUHHHHAAAAHHAAAA!!!!!");
System.exit(0);
break;
}
break;
}
break;
} while (true);
}
}

如果条件应该正常工作,请尝试使用内部中断

例:

if(choice == '4')
break;
System.exit(0);
break;

可以写成

return;

您缺少要求用户输入下一个输入的代码行。 试试这个:

switch (choice) {
case '1':
p("nAs prepare to enter the house, The door slowly creaks open.");
p("nYou enter the house and the door slams shut.");
p("What do you do????");
p("         1. Try to open the door.");
p("         2. Find the nearist closet and hide.");
p("         3. Continue onward.");
p("         4. Faint and end game.");
choice = in.next().charAt(0);
break;

使用此行,再次要求用户输入,然后应用程序终止。

所以你的代码做什么,是它打印第一个带有"请做出选择"和 3 个选项的文本块。然后你抓住用户输入(所以'1'(。

它输入第一个开关语句并进入case '1'。它打印它需要的内容并脱离该 switch 语句。

然后你进入while (choice == '1')循环。在这里,您可以立即输入第二个switch case,而无需等待并获取新输入。 因为您不等待并获取新输入,所以choice的值仍然'1'

因此,在第二个switch case,您立即输入case '1'。 在这种情况下,它会打印需要打印的内容。然后你突破那个switch case,打破while (choice == '1')循环,最后打破do while循环。

最新更新