HELP PLEASE ! Beginner Java Programming - Practice implementing loops, input val
ID: 3869268 • Letter: H
Question
HELP PLEASE !
Beginner Java Programming - Practice implementing loops, input validation, and the Random class.
Create a dice rolling simulator using the loops of your choice and Java's random number generator.
1. Prompt the user to enter the number of times to roll a six-sided die. The user can roll a die no more than 10 times. If the user inputs a value less than 1 or greater than 10, the user should be prompted again until an appropriate input value is read.
2. Use a loop that iterates the appropriate number of times and does the following:
- ``rolls the die" by getting a random value between 1 and 6
- adds the roll value to a variable that keeps track of the sum of all roll values
- outputs the roll value
- increments a ``counter" variable used to keep track of how many times the loop has iterated
3. After all rolls have completed, compute and output the average roll value.
Example:
My Program so far :
import java.util.Random;
import java.util.Scanner;
public class Lab10 {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
int userIn;
do{
System.out.println("Enter a number rolls (1-10):");
userIn = input.nextInt();
}while( userIn<1 || userIn>10);//re-prompts the user until they enter a value 1-10
Random userDie = new Random();
if(userIn>1 || userIn<10)
{
int roll =userDie.nextInt(6)+1;// random value between 1-6
System.out.println("You rolled a " + roll);
}
System.out.println();
input.close();
}
}
Thank you !!
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random userDie = new Random();
int userIn,ucopy=0;
double sum=0.0,avg;
do {
System.out.print("Enter a number rolls (1-10):");
userIn = input.nextInt();
} while (userIn < 1 || userIn > 10); //re-prompts the user until they enter a value 1-10
//while loop userIn times
while (ucopy != userIn) {
int roll = userDie.nextInt(6) + 1; // random value between 1-6
sum = sum+roll;
ucopy++;
System.out.println("You rolled a " + roll);
}
avg = sum/userIn;
System.out.printf("Average roll: %.2f ",avg);
input.close();
}
}
/*
Enter a number rolls (1-10): 0
Enter a number rolls (1-10): 11
Enter a number rolls (1-10): 5
You rolled a 1
You rolled a 6
You rolled a 3
You rolled a 1
You rolled a 4
Average roll: 3.00
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.