0

I'm trying to write a simple little text adventure, DnD-style thing here as practice, but I have run into a problem that I can't for the life of me find a solution for.

I need to create a loop for when the user types the text response incorrectly because I don't want it responding to just anything the user types in and don't want to force the user to restart the entire program. I know about the do/while loop, but I have no idea how to implement it in a text input check because everyone uses it with numbers, not text.

Here's the code:

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 Answer 1

1

Move String u_r1 = kb.next(); as the first statement in the while loop should work for you (since you break on encountering the right input).

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
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. It was staring me right in the face. Thanks so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.