Dice Roll Histogram with Loops - java

I have a problem in my class that I just can't figure out.
This is the question:
The purpose of this quiz is to reinforce the understanding of using loops and counting as well as reviewing the use of random numbers.
Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like # that number of times. Two dices will be used in each roll.
Example:
Histogram showing total number of dice rolls for each possible value.
Dice roll statistics (result varies):
2s: ######
3s: ####
4s: ###
5s: ########
6s: ###################
7s: #############
8s: #############
9s: ##############
10s: ###########
11s: #####
12s: ####
~~~~~~~~~~~~~~~~~~~~~
I haven't been able to get the program to print the histogram in the example above.
And this is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int numOnes = 0;
int numTwos = 0;
int numThrees = 0;
int numFours = 0;
int numFives = 0;
int numSixes = 0; // Tracks number of 6s found
int numSevens = 0; // Tracks number of 7s found
int numEights = 0;
int numNines = 0;
int numTens = 0;
int numElevens = 0;
int numTwelves = 0;
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
if (rollTotal == 1) {
numOnes = numOnes + 1;
}
if (rollTotal == 2) {
numTwos = numTwos + 1;
}
if (rollTotal == 3) {
numThrees = numThrees + 1;
}
if (rollTotal == 4) {
numFours = numFours + 1;
}
if (rollTotal == 5) {
numFives = numFives + 1;
}
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
if (rollTotal == 7) {
numSevens = numSevens + 1;
}
if (rollTotal == 8) {
numEights = numEights + 1;
}
if (rollTotal == 9) {
numNines = numNines + 1;
}
if (rollTotal == 10) {
numTens = numTens + 1;
}
if (rollTotal == 11) {
numElevens = numElevens + 1;
}
else if (rollTotal == 12) {
numTwelves = numTwelves + 1;
}
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
System.out.println("1s: " + numOnes);
System.out.println("2s: " + numTwos);
System.out.println("3s: " + numThrees);
System.out.println("4s: " + numFours);
System.out.println("5s: " + numFives);
System.out.println("6s: " + numSixes);
System.out.println("7s: " + numSevens);
System.out.println("8s: " + numEights);
System.out.println("9s: " + numNines);
System.out.println("10s: " + numTens);
System.out.println("11s: " + numElevens);
System.out.println("12s: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Any help would be very appreciated.

Have a loop like this where you have your print statements.
Modify your code so that instead of taking new variables every time have them in a array so that you can loop through them.
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int[] numValues=new int[12];
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
numValues[rollTotal]++;
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
for(int i=2;i<=12;i++)
{
System.out.print(i+"s: ");
for(int j=0;j<numVales[i];j++)
{
System.out.print("#");
}
System.out.println();
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Let me know if you need clarification on the problem.

You can do something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//You can directly set the seed during the object creation.
Random random = new Random(System.currentTimeMillis());
// This array is used to keep the value of your dice (2 - 12)
int [] histogram = new int[13];
while(true) {
System.out.println("Enter number of rolls: ");
int numberOfRolls = scanner.nextInt();
//If you enter 0, you can simply terminate the program
if(numberOfRolls == 0) break;
for(int i = 0; i < numberOfRolls; i++) {
int rolledValue = (random.nextInt(6) + 1) + (random.nextInt(6) + 1);
histogram[rolledValue]++;
}
//Print the result to your console.
for(int i = 2; i < histogram.length; i++) {
System.out.print("Total: " + i + " ");
for(int j = 0; j <histogram[i]; j++) {
System.out.print("#");
}
System.out.println();
}
}
}
That code will have a result as below:
Enter number of rolls: 7
Total: 2
Total: 3 #
Total: 4
Total: 5 ##
Total: 6
Total: 7 ###
Total: 8
Total: 9
Total: 10 #
Total: 11
Total: 12

Looks like you're really close. You just need to print the number of # for each int variable you have. The following will do that for the numTwos:
char[] chars = new char[numTwos];
Arrays.fill(chars, '#');
String result = new String(chars);
System.out.println(result);
You can put the whole thing in a loop of 12 to print it for all of them.

Related

Is there perhaps a way of finding the above and below average

I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}
This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}
Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}
You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}
Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}

This program should ask user for the max num to print out to and then calculate each number starting from 1 to the maximum along with it squared

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());

How to count a sum of numbers multiple 2, 3, 5 and 7?

When I try to count a sum of multiple numbers I got not correct data. Instead of big results, programm shows little numbers like: SUMM OF 2 = 100. It can't be, because the last number multiple 2 is 98.
public class Array {
public static void main(String[] args){
multipleNums();
}
static void multipleNums(){
int i = 0;
int multTwo = 0;
int multThree = 0;
int multFive = 0;
int multSeven = 0;
int summTwo = 0;
int summThree = 0;
int summFive = 0;
int summSeven = 0;
for(i = 0; i <= 100; i++){
if(i == 0){
System.out.println("0 multiple 0");
}else if(i%2 == 0){
System.out.println(i + " multiple 2");
summTwo = i + multTwo;
}else if(i%3 == 0){
System.out.println(i + " multiple 3");
summThree = i + multThree;
}else if(i%5 == 0){
System.out.println(i + " multiple 5");
summFive = i + multFive;
}else if(i%7 == 0){
System.out.println(i + " multiple 7");
summSeven = i + multSeven;
} else {
System.out.println(i);
}
}
System.out.println();
System.out.println("SUMM OF 2 " + summTwo);
System.out.println("SUMM OF 3 " + summThree);
System.out.println("SUMM OF 5 " + summFive);
System.out.println("SUMM OF 7 " + summSeven);
}
}
Your always adding multTwo, multThree etc. which are 0. You should change your code to use sumXY += i
Change the line
summTwo = i + multTwo;
to
summTwo += i ;
do this for other variables, 3,5,7..

Issues when taking Dice one and Dice two with the same value and adding it to an integer

I am currently trying to get the number of times the two dice have identical values. This is what I have so far.
public static void main(String [] args)
{
System.out.print("Enter the amount of rolls you want to do: ");
Scanner scan = new Scanner(System.in);
int r = scan.nextInt();
final int FACES = 6, ROLLS = r;
int [] rollCount = new int [FACES];
int [] rolCount = new int [FACES];
Die d1 = new Die();
Die d2 = new Die();
int myRoll = 0;
int myRollTwo = 0;
int Ident = 0;
int i = 0;
while (i <= 1)
{
int ii = 0;
int iii = 0;
for (ii = 1; ii <= ROLLS; ii++)
{
myRoll = d1.roll();
rollCount[myRoll - 1]++;
}
for (ii = 1; ii <= ROLLS; ii++)
{
myRollTwo = d2.roll();
rolCount[myRollTwo - 1]++;
iii++;
}
if (myRoll == myRollTwo)
{
Ident++;
}
if (iii == ROLLS)
{
i++;
}
}
System.out.println("Die Number\tDie One\tDie Two\tTotal\t Amount of Identical Rolls");
for (i = 0; i < rollCount.length; i++)
{
System.out.println((i + 1) + "\t\t\t" + rollCount[i] + "\t\t" + rolCount[i] + "\t\t" + ((rollCount[i] + rolCount[i])*(i + 1)) + "\t\t" + Ident);
}
}
I know that the if statement near the end of the while loop wouldn't work because it would only do it once, so how exactly would I go about getting the number of times the two dice were the same?

Generate additional random number from array of 20 integers

I am having trouble with this, I need to generate an additional single random number that has the same 1-10 span. I already have the code for the random generator that produces my 20 integer array of random numbers but how do I generate a single random number in the same span within the same method. This is what I have so far and it keeps giving me random number 0: from my 20 integer array. Thanks in advance.
import java.util.Scanner;
import java.util.Random;
class Main{
public static final Random RND_GEN = new Random();
public int[] createNum(int[] randomNumbers) {
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
for (int i = 0; i < 1 ; i++){
randomNumbers[i] = RND_GEN.nextInt(10) + 1;
}
return randomNumbers;
}
public void printNum(int[] randomNumbers){
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Number " + i + " : " + randomNumbers[i]);
}
for (int i = 0; i < 1; i++){
System.out.println("Single # is: "+randomNumbers[i]);
}
}
public void searchArray(int[] randomNumbers, int numSearch) {
int count = 0;
for (int i : randomNumbers) {
if (i == numSearch) {
count++;
}
}
if (count == 0) {
System.out.println("Number # " + numSearch + " was not found!");
} else {
System.out.println("Number #" + numSearch + " occurred " + count + " times.");
}
}
public void run() {
Scanner inputReader = new Scanner(System.in);
int x = 1;
do {
int[] numbers = new int[20];
numbers = createNum(numbers);
printNum(numbers);
System.out.print("Restart Program?, Enter 1 for YES, 2 for NO: ");
x = inputReader.nextInt();
} while (x == 1);
}
public static void main(String[] args) {
Main go = new Main();
go.run();
}
}
This loop in printNum() looks suspicious:
for (int i = 0; i < 1; i++){
System.out.println("Single # is: "+randomNumbers[i]);
}
It will always print the first element of randomNumbers. It's not clear what you want, but if I had to guess it would be:
int i = RND_GEN.nextInt(randomNumbers.length);
System.out.println("Single # is: " + randomNumbers[i]);
which will print some random element of randomNumbers. Or perhaps:
int i = 1 + RND_GEN.nextInt(10);
System.out.println("Single # is: " + i);
which will print an independent random number between 1 and 10 (inclusive).
P.S. You have another one of those suspicious loops earlier in your code in createNum() as well. However, that one seems harmless in that it just assigns a second random number to randomNumbers[0].

Categories

Resources