【问题标题】:How can i make a specific section of my code loop?如何制作代码循环的特定部分?
【发布时间】:2021-12-17 22:58:44
【问题描述】:

我开始制作这个小骰子游戏,但我需要一些帮助来弄清楚如何在每次尝试失败后使重试部分循环。

目前游戏重新开始并要求玩家重新输入他们的名字。 我想要的是让用户重新输入他们的猜测 每一次,直到他们成功。

import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

public class Main {

    public static void main (String[] args) throws IOException {

        boolean run = true;

        while (run) {

            String[] input = new String[]{"1", "2", "3", "4", "5", "6"};
            String[] sorry = new String[]{"If at first you don't succeed...", "Your luck will improve...", "Don't give up...", "Not this time..."};
                Random dice = new Random();

            int select = dice.nextInt(input.length);

            Scanner scan = new Scanner(System.in);
            System.out.println( "Hi there, may I please have your name?");
                String name = scan.nextLine();
            System.out.println("What a nice name...");
            System.out.println("ok "+name+", please choose a number between 1 and 6");
                String play = scan.nextLine();
                System.out.println(input[select]);

            if (!input[select].equals(play)) {
                System.out.println(sorry[select]+" try again");


            if (input[select].equals(play))
                System.out.println("Bingo!!! "+name+" you've won 1 million imaginary dollars!");
                System.out.println("would you like to play again \"Y\" or \"N\"");
                String yes = "y";
                String no = "n";
                String answer = scan.nextLine();

                if (answer.equals(yes)) {
                    continue;
                }

                if (answer.equals(no)) {
                    System.out.println("Thank you for playing "+name+". Good bye!");
                    break;
                }

            }
        }
    }
}

【问题讨论】:

  • 一些提示:将初始化移出循环是一个很好的约定。您无需在每个循环中重新定义inputsorrydice,因此您可以将它们移到while(run) 行上方。如果您不需要每次都询问此人的姓名,请将其移到循环之外(while(run) 行上方)。循环中的所有内容每次都会运行,因此请弄清楚您要重复哪个部分并将其他所有内容移出它。
  • 是的,这确实更有意义。谢谢! :)

标签: java loops


【解决方案1】:

您可以使用while 循环!在重试部分,将if 更改为while 循环。

static String play; // Define it (not assign) outside of method

while (!input[select].equals(play)) {
            System.out.println(sorry[select]+" try again");
            System.out.println("ok "+name+", please choose a number between 1 and 6");
            play = scan.nextLine();
}

W3Schools定义while循环:

只要指定条件为真,while循环就会循环遍历一段代码

【讨论】:

    【解决方案2】:

    将询问名称的打印语句放在while循环之外。

    Scanner scan = new Scanner(System.in);
    System.out.println("Hi there, may I please have your name?");
    String name = scan.nextLine();
    while(run){
    // your code
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2018-12-03
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多