## find average between two random numbers in java and then count how many times a number was rolled with a switch statement

java roll dice 100 times

java dice roll program

java dice roll array

write a code fragment that rolls a die 100 times and counts the number of times a 3 comes up.

write a program that simulates the rolling of two dice

dice simulation.java while loop

pair of dice java

Hello again StackOverflow,

New question needing help with some code. So far I'm making a random number generator that will choose a random number between 1-100 for rolls and then roll a "die" for a number **between 1-6**. It then prints out every roll and number rolled up to said a random number between 1-100.

The problem I'm having is this. Let's be simple and say that the random number generated **between 1-100** is 9 and the die rolls in order for each roll is

1, 6, 3 , 5, 4, 2, 1, 6, 6

The output is fine and the averaging is fine. The new problem I have is this:

Add to the program a switch statement to keep track of how many times each number comes up.

I have a basic idea on how to do this but I am a bit confused on how to actually go along with this and execute it. Help please

My Current Code: (UPDATE: The first problem has been solved, the new problem is said above)

class Main { public static void main(String[] args) { int rolls = (int)(Math.random()*100); System.out.println("Number of Rolls: "+ rolls); System.out.println(" "); System.out.println("Rolls\t\tNumber"); double sum = 0; for (int i = 1; i <= rolls ; i++) { int dienumber = (int)(Math.random()*6+1); sum += dienumber; System.out.println(i + "\t\t" + dienumber); } double average = sum /(1.0*rolls); System.out.println(" "); System.out.printf("%-2s%.2f\n","Average: ", average); } }

Thanks again

Sum all the random numbers in a variable, and divide by number of rolls

double sum = 0; for (int i = 1; i <= rolls ; i++) { int dienumber = (int)(Math.random()*6+1); sum += dienumber; System.out.println(i + "\t\t" + dienumber); } double avg = sum / rolls;

**Javanotes 8.1, Solution to Exercise 2, Chapter 2,** You can simulate rolling one die by choosing one of the integers 1, 2, 3, 4, 5, or 6 at random. The number you pick represents the number on the die after it is rolled. does the computation to select a random integer between 1 and 6. variables to represent the numbers showing on each die and the total of the two dice. Java Program To Calculate Average Of N Numbers. in Java Programs, Uncategorized Comments Off on Java Program To Calculate Average Of N Numbers. Java program to calculate the average of N numbers. Here is the code to calculate the average of N numbers or average of 2 or 3 numbers.

You can as well collect you random numbers into an array and calculate average using streams:

int rolls = (int)(Math.random()*100); int rollsArray[] = new int[rolls]; for (int i = 1; i < rollsArray.length ; i++) { rollsArray[i] = (int)(Math.random()*6+1); } System.out.println(Arrays.stream(rollsArray).average()); // example output OptionalDouble[3.0]

**Java Programing: Solution to Programming Exercise,** Exercise 5.1: In all versions of the PairOfDice class in Section 2, the instance Your class will need methods that can be used to find out the values of die1 and die2. that counts how many times a pair of dice is rolled, before the total of the two to be // a random number between 1 and 6. die1 = (int)(Math.random()*6) + 1; Java provides support for generating random numbers primarily through the java.lang.Math and java.util.Random classes. In this post, I will discuss different ways to generate random numbers based

You can create a int variable that will count the total inside the loop after each roll. After the loop, just divide this total by your number of rolls.

class Main { public static void main(String[] args) { int rolls = (int)(Math.random()*100); int total =0 System.out.println("Number of Rolls: "+ rolls); System.out.println(" "); System.out.println("Rolls\t\tNumber"); for (int i = 1; i <= rolls ; i++) { int dienumber = (int)(Math.random()*6+1); System.out.println(i + "\t\t" + dienumber); total += dienumber; } double average = total /(1.0d*rolls); System.out.println("Average = "+average); } }

**Big Java: Early Objects,** You might think that on average the drunkard doesn't move very far because the choices cancel each other out, but that is not the case. If m is chosen as 232, then you can compute rnew = a ⋅ rold + b because the truncation of an to be can any be random any value number between between 0 degrees 0 and and 2. Number of digits: 4. In this program, while loop is iterated until the test expression num != 0 is evaluated to 0 (false). After first iteration, num will be divided by 10 and its value will be 345. Then, the count is incremented to 1. After second iteration, the value of num will be 34 and the count is incremented to 2.

Functional approach (Java 1.8+):

{ // ... double average = IntStream.range(0, rolls) .map(this::roll) .average() .orElse(0); System.out.println("Average : " + average); } private int roll(int i) { int dieNumber = (int) (Math.random() * 6 + 1); System.out.println(i + "\t\t" + dieNumber); return dieNumber; }

**[PDF] Methods: A Deeper Look,** Exercise 6.3 Solution: MathTest.java. 2. // Testing the Math class methods. 3. 4 2. // Calculate the volume of a sphere. What is the value of x after each of the following statements is executed? a) What does it mean to choose numbers “at random?” ANS: Every number has an equal chance of being chosen at any time. Java program to calculate the average of marks. Here we cover five simple ways to find out the average of marks in Java programming. If you know the basics of coding, you can even write more than 5+ ways. However, as a newbie, we share the program in 5 different ways. Do check it out.

This generates a number in the range [0, 99], not [1, 100]:

int rolls = (int)(Math.random()*100);

Performance-wise it's a good idea to re-use a Random instead of calling Math.random repeatedly:

public class Main { private static final Random RANDOM = new Random(); public static void main(String[] args) { int rolls = RANDOM.nextInt(99) + 1;

Note that, if you ever use randomness for generating security sensitive things like activation codes, use SecureRandom instead.

To calculate the average just keep track of the sum:

int sum = 0; for (int i=1; i <= rolls ; i++) { int dienumber = RANDOM.nextInt(6) + 1; System.out.println(i + "\t\t" + dienumber); sum += dieNumber; } double average = ((double) sum) / rolls; System.out.printf("Average: %s%n", average);

You could also create a separate class to calculate the average, be all object-oriented and score brownie points for effort:

public class Average { private double total; private int count; public synchronized void add(double value) { total += value; count++; } public double getAverage() { if (count == 0) { throw new IllegalStateException("Cannot calculate average, no values added"); } return total / count; } public double getTotal() { return total; } public int getCount() { return count; } public synchronized void reset() { total = 0; count = 0; } }

And your code would use this like so:

Average average = new Average(); for (int i=1; i <= rolls ; i++) { int dienumber = RANDOM.nextInt(6) + 1; System.out.println(i + "\t\t" + dienumber); average.add(dieNumber); } System.out.printf("Average: %s%n", average.getAverage());

EDIT: As a general rule of thumb, when someone (or your homework assignment) tells you to add a switch statement: don't do it. Switch statements are evil pools of gunk which accumulate demons and reek of the foul stench of a project room filled with 2000 PHP developers. Don't. (I can recommend reading Clean Code by Uncle Bob)

But seriously: keeping track of how many times a number comes up is a valid requirement. Telling the developer to use a switch statement for this is not. This is a tendency you will come across a lot with users: they tend to specify the solution they envision, instead of formulating the problem they want to solve. This is dangerous, since if you buy into it you may very well start off on the wrong foot. The solution suggested by stakeholders is very often not optimal and rooted in their past domain experience, not technical and design knowledge. `</rant>`

Instead, in this case, use a Map to keep track of the outcomes. If the cases are more diverse than just keeping track of a value like here, revert to the strategy pattern to solve the problem in an object-oriented way.

Since I already proposed the lovely 'Average' class we can rename this to 'Statistics' and adorn it with a Map:

public class Statistics { private int total; private int count; private Map<Integer, Integer> distribution = new HashMap<>(); public synchronized void add(int value) { total += value; count++; updateDistribution(value); } private void updateDistribution(int value) { Integer count = distribution.get(value); if (count == null) { count = 0; } count++; distribution.put(value, count); public double getAverage() { if (count == 0) { throw new IllegalStateException("Cannot calculate average, no values added"); } return total / count; } public double getTotal() { return total; } public int getCount() { return count; } public synchronized void reset() { total = 0; count = 0; distribution.clear(); } public int getCount(int value) { Integer count = distribution.get(value); if (count == null) { count = 0; } } }

**Chapter 5: Program Logic and Indefinite Loops,** Use while statements; Use fencepost loops; Use the boolean type; Use while statements to handle Add a counter to count how many times the body of the loop is executed. After that, the next number is the sum of the two previous numbers. The Random class is found in the java.util package. how would you get:. 1) java.util.Random. For using this class to generate random numbers, we have to first create an instance of this class and then invoke methods such as nextInt(), nextDouble(), nextLong() etc using that instance. We can generate random numbers of types integers, float, double, long, booleans using this class.

**Conditionals and Loops,** The following code fragment uses an if statement to put the smaller of two int values in The while loop enables us to execute a group of statements many times. It uses several nested if-else statements to test from among a number of mutually With Math.random() we get points that are randomly distributed in the 2-by-2 Here is a code snippet, which can be used to generate random numbers in a range between 0 to 10, where 0 is inclusive and 10 is exclusive. This code uses Math.random() method, which returns pseudo-random number in a range 0.0 to 1.0, where later is exclusive, by multiplying output with and then type casting into int, we can generate random integers in any range.

**Random numbers for experimental probability (video),** "o"; "Wogo BY KRISTIN HISTETTER, EUUIPMENT EDITDR There are all sorts of creative and deceitful ways to. 2000 W WWW.BACKPACKER.COM. Java program to calculate the sum of N numbers using arrays, recursion, static method, using while loop. Here is the complete Java program with sample outputs. You can learn more tutorials here and Java interview questions for beginners. With the following program, you can even print the sum of two numbers or three numbers up

**Backpacker,** Turns out the former high-ranking politician from Mexico had skipped two checkpoints. SPEND According to Visa, men lose track of $3,078 every year, on average. Finding an exercise bike at my door would be great for rainy days when my For example, an increasing number of New Orleans visitors are p.ting down In this article, we will show you three ways to generate random integers in a range. java.util.Random.nextInt; Math.random; java.util.Random.ints (Java 8) 1. java.util.Random. This Random().nextInt(int bound) generates a random integer from 0 (inclusive) to bound (exclusive). 1.1 Code snippet.

##### Comments

- Add dienumber to another variable, and just divide by rolls at the end. (Keeping in mind that if the new variable is an int, it will ignore any floating point. 7/3 = 2, for example.)
- Is this your homework?
- I did this and now the average prints out as 3.00 everytime.
- @neil I'm getting good results. Can you share your updated code?
- edited the code above because I have a new problem. Updated code is above, I used other commenters code and theirs worked fine.
- @neil
`sum`

should be`double`

, not`int`

.`int / int`

will result in`int`

. It always 3 because the small range of numbers. Casting`sum`

to`double`

`double avg = (double)sum / rolls;`

will also do the trick.