直接代码循环文本输入检查直到正确?

时间:2018-08-25 05:26:48

标签: java

我试图在这里写一个简单的小文字冒险,即DnD风格的东西,但是我遇到了一个我一生都找不到解决方案的问题。

我需要为用户输入错误文本响应时创建一个循环,因为我不希望它仅响应用户键入的任何内容,也不想强迫用户重新启动整个程序。我知道do / while循环,但是我不知道如何在文本输入检查中实现它,因为每个人都使用数字而不是文本。

代码如下:

package drake;

import java.util.*;

public class drake {
public static void main(String[]args) {

    Random rand = new Random();
    Scanner kb = new Scanner(System.in);



    int ini_d = rand.nextInt((17 - 12) + 1) + 12;
    int ini_u = rand.nextInt((20 - 1) + 1) + 1;
    int cha_d = 16;
    int cha_u = 15;
    int r_d = rand.nextInt((20 - 11) + 1) + 11;
    int r_u = rand.nextInt((20 - 1) + 1) + 1;
    int hp_d = 50;
    int hp_u = 30;
    int dam_d = rand.nextInt((12 - 7) + 1) + 7;
    int dam_u = rand.nextInt((17 - 12) + 1) + 12;

    System.out.println("A young dragon towers over you, it's reptilian eyes digging into your very soul. It roars at you, posing a challenge.");
    System.out.println("Type 'roll' to roll for initiative.");
    String u_r1 = kb.next();

    while(true)
        if (u_r1.equalsIgnoreCase ("roll")) {

        System.out.println(ini_d);
        System.out.println(ini_u);
        break;
        }
        else {
            System.out.println("Your input was invald. Please try again.");
            //I need to give the user another chance to input text, and then direct the program to check it again and again until it's typed in correctly.
            return;
        }


    if (ini_d >= ini_u) {
        System.out.println("The dragon rushes towards you in an attempt to attack you.");
    }




}

}

1 个答案:

答案 0 :(得分:1)

String u_r1 = kb.next();作为while循环中的第一条语句应该对您有用(因为您break遇到了正确的输入)。

while(true) {
    String u_r1 = kb.next();
    if (u_r1.equalsIgnoreCase("roll")) {
        System.out.println(ini_d);
        System.out.println(ini_u);
        break;
    } else {
        System.out.println("Your input was invald. Please try again.");
    }
}
//Rest of the code