Home > front end >  How can i make a specific section of my code loop?
How can i make a specific section of my code loop?

Time:11-04

I started working on this little dice game but I need some help figuring out how to make the try again section loop after each failed attempt.

Currently the game restarts and asks the player to re-enter their name. What I would like is for the user to just re-enter their guess each time until they become successful.

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;
                }

            }
        }
    }
}

CodePudding user response:

Put the print statement that asks name outside the while loop.

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
}

CodePudding user response:

You can use a while loop! At the try again section, change the if to a while loop.

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();
}

Definition of while loop from W3Schools:

The while loop loops through a block of code as long as a specified condition is true

  • Related