Natasha Shorrock Natasha Shorrock - 1 month ago 13
Java Question

I'm trying to add a loop into my dice roller program

I'm trying to get a dice roller happening and I'm having some difficulty adding a loop somewhere so the program doesn't quit after one roll. I want to ask the user if they want to roll and it rolls by saying "y." I want to end the program by asking the user the same question but it ends with "n"

/*
Natasha Shorrock
Assignmnt A6
11/07/16
*/
package diceroller;
import java.util.Random;
import java.util.Scanner;

public class DiceRoller {
public static void main(String []args) {
System.out.println(" Do you want to roll the dice? ");
Random dice = new Random();
Scanner input = new Scanner(System.in);
int faces;
int result;

System.out.println("Dice Roller\n");
System.out.println("How many faces does the dice have?");
faces = input.nextInt();
result = dice.nextInt(faces) + 1;
System.out.println("\nThe dice rolled a " + result );
}//Dice Roller
}//class DiceRoller

Answer

You nedd to read the answer after the

System.out.println(" Do you want to roll the dice? ");

with a input.nextLine(); and loop while the input is "y"

the while(condition) loop is excuted while the condition is true

The while statement continually executes a block of statements while a particular condition is true. The while and do-while Statements

for your exemple you can try this code :

public static void main(String[] args) {
    Random dice = new Random();
    Scanner input = new Scanner(System.in);
    System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
    String answer = input.nextLine(); // reading the input

    // we check if the answer is equals to "y" to execute the loop,
    // if the answer is not equals to "y" the loop is not executed
    while ("y".equals(answer)) {  
        System.out.println("Dice Roller");
        System.out.println("How many faces does the dice have?");
        int faces = input.nextInt();
        int result = dice.nextInt(faces) + 1;
        input.nextLine(); // to read the newline character (*)
        System.out.println("The dice rolled a " + result);
        System.out.println("Do you want to roll the dice? (y: yes / q: to quit)");
        answer = input.nextLine();
    }
}

for more about the while and do-while, please visit this toturial

(*) to understand the use of nextLine() after a call to nextInt() please visit Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods