【问题标题】:Dice Rolling Game掷骰子游戏
【发布时间】:2015-12-24 22:57:00
【问题描述】:

所以在这个掷骰子游戏中,用户输入的内容必须遵循 xdy 的格式,其中“x”是骰子的数量,“y”是骰子的面数。如果输入不符合格式,程序应该要求用户输入另一个输入。

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Scanner user_input = new Scanner(System.in);

    String input;
    System.out.println("Please enter the number and type of dice to roll in the format <number>d<sides>.");
    input = user_input.nextLine();  

    while()
            {
            System.out.println("Input is not valid. Please enter a new input");
            input = user_input.nextLine();
            }

    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(5);

我的问题是,如何让while 循环检查两个整数之间的字符?

【问题讨论】:

    标签: java validation while-loop character dice


    【解决方案1】:

    一个优雅的方法是使用Pattern

    Pattern p = Pattern.compile("\\d+d\\d+");
    input = user_input.nextLine();  
    
    while (!p.matcher(input).matches) {
        System.out.println("Input is not valid. Please enter a new input");
        input = user_input.nextLine();
    }
    

    【讨论】:

    • 如果需要超过 9 个骰子和/或超过 9 个面的骰子怎么办? \\d+d\\d+ 不是为此目的更好的正则表达式吗?另外,为什么不使用Pattern 来捕获骰子的数量和骰子的面数?
    • @Bobulous 好点,谢谢!根据您的建议进行了编辑和改进。
    【解决方案2】:

    将 numberOfSides 和 number OfDice 分成两个变量,然后对它们做任何你想做的事情。

    String input="6d3";
    int numSides=Integer.parseInt(input.split("d")[0]);
    int numDice=Integer.parseInt(input.split("d")[1]);
    

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多