在java中是否有一个命令使程序回到循环的开头

use*_*790 1 java command loops switch-statement

我试图在java中进行打字冒险类游戏,但是我需要一个至少类似于标题中的命令的命令,这里是代码

import java.util.Scanner;

public class MyFirstGameInJava {

public static void main(String[] args) {

System.out.println("Greetings, Enter your name and you may start your quest!");
Scanner Username = new Scanner(System.in);
String name = Username.nextLine();
System.out.println("Greetings " + name );
System.out.println("Welcome to an Unnamed Typing Advanture");
System.out.println("You find yourself on an island with very few trees, you can either hit a tree, or walk along");

String sc = Username.nextLine();

switch(sc){

case "Hit tree":
System.out.println("A coconut falls from the tree");
System.out.println("You can either eat the coconut or throw it");
break;
case "Walk":
System.out.println("You walk for a mile and find a village");
System.out.println("The village appears empty, you can either scream to see if anybody is there, or you can keep walking");
break;
default :
System.out.println("Nothing happens...");
}   

String sc1 = Username.nextLine();


switch(sc1){

case "Eat coconut":
System.out.println("You ate the coconut and got poisoned");
System.out.println("You died...");
break;
case "Throw coconut":
System.out.println("By throwing the coconut, you awaken a tiger and he eats you");
System.out.println("You are dead");
break;
case "Scream":
System.out.println("As soon as you scream, a man shoots you down from a window from one of the houses");
System.out.println("You died...");
break;
case "Walk":
System.out.println("You walked through the village, and you find a boat and leave the island");
System.out.println("You win! Updates coming soon!");
break;
default:
System.out.print("Nothing happend");



}

}

}
Run Code Online (Sandbox Code Playgroud)

每当用户键入除了需要之外的其他内容时,就会发生默认情况,但我需要它返回到循环的开头,因此用户可以键入其他一种情况.

And*_*mas 6

您可以使用该continue语句继续下一次迭代.

也就是说,我没有在示例代码中看到循环.你可以循环使用for,whiledo/while.该DO /时循环至少执行一次-这通常是你想要询问用户问题时该怎么办.

这个分支语句的Java教程continuefor循环中提供了一个语句示例.

   for (int i = 0; i < max; i++) {
        // interested only in p's
        if (searchMe.charAt(i) != 'p')
            continue;

        // process p's
        numPs++;
    }
Run Code Online (Sandbox Code Playgroud)