java 返回循环开始,Java中是否有命令使程序返回循环的开头

I am trying to make a typing adventure kind of game in java, however i need a command at least similar to the one in the title, here is the code

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");

}

}

}

Whenever the user types something else than required, the default case happens, but i need it to go back to the start of the loop, so the user can type one of the other cases.

解决方案

You can use the continue statement to continue to the next iteration.

That said, I don't see a loop in your sample code. You can loop with a for, while or do/while. The do/while loop executes at least once -- which is typically what you want to do when asking the user a question.

This Java tutorial for Branching Statements provides this example of a continue statement in a for loop.

for (int i = 0; i < max; i++) {

// interested only in p's

if (searchMe.charAt(i) != 'p')

continue;

// process p's

numPs++;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值