Rolling-dice class and driver - java

alright so i have to write a class and driver that has the user input the number of dice and the number of rolls. and then i have to make an array based off the number of dice * 6. but i get errors. like arrayindexoutofboundsexception.
after i make the array i have to fill it with random numbers and use a histogram to display the program. so the program should look like this
Please give any positive help here, im new to this programing this and i would love to learn more. also i cant seem to figure out if statements for the Y/N area to start the program
Welcome to the dice-rolling simulator!
Do you wish to run a simulaton? Y/N: x
that was an invalid option. Please try again.
Do you wish to run a simulation? Y/N: y
How many dise di you wish to roll? 2
How many rolls to you wish to make? 100000
2:######
3:####
4:###########
5:#####
6:##
7:#
8:
9:##########
10:###
11:##############
12:######
//I had to you # signs because * would not work here
here is my program updated! how do i create the histogram?
package dice;
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static Scanner in = new Scanner (System.in);
private int dice = 0;
private int roll = 0;
private int start;
private int[] diceAr;
private int[] rollAr;
private int simDice;
private String star = "*";
//****************************************************************
public Dice()
{
System.out.println("Welcome to the dice-rolling simulator!\n");
System.out.println("Do you wish to run a simulation? Y/N; ");
//start = in.nextInt();
while (true) {
System.out.print ("How Many Dice Do You Want To Roll? ");
dice = in.nextInt();
simDice = (dice * 6)-1;
diceAr = new int[simDice];
if (dice > 0)
break;
}
while (true) {
System.out.print ("How Many Times Do You Want To Roll? ");
roll = in.nextInt();
rollAr = new int[roll];
if (roll > 0)
break;
}
}
//**********************************************
// public void display()
// {
//
for ( int i = 0; i < simDice; i++)
// {
// diceAr[i] = (int)(Math.random()* simDice);
//
// }
// for(int i = 0; i<simDice; i++)
// {
// System.out.println((i + dice) + ". " + diceAr[i]);
// }
//
// }
//*********************************************************
public void display(int diceAr[], int simDice, int roll)
{
for(int i=0; i < simDice; i++)
{
diceAr[i] = (int) (Math.random()* simDice);
}
for(int i=0; i < roll; i++)
{
}
}
}

Judging from the wording of the questions the program asks and the sample histogram you give, it appears the assignment is to write a program to simulate rolling N dice M times and then make a histogram of the results (i.e. the sum of the numbers on the dice on each roll) of the rolls. So if you enter 3 dice and 100 rolls, it should be as if you rolled 3 dice by hand 100 times.
Even aside from the ArrayIndexOutOfBoundsException issue, that is not what your code is doing. Since this is admitted homework I'm not going to give any code, at least not at this point. But I do have some suggestions/questions that might help you think about the problem better and perhaps you can show us how you've changed your code after thinking about it.
First, consider actually doing the task manually. Find two or three dice and roll them, say, 20 times, and make a histogram of the result on paper. You may find just doing that by itself will give you lots of insight into what your program will have to do and keep track of.
Next, here are some questions that might help focus your thinking:
If you are rolling 2 dice, what's the lowest possible result of a roll? What's the highest?
If you are rolling 3 dice, what's the highest and lowest possible result of a roll?
If you are rolling N dice, what's the highest and lowest possible result of a roll?
When you simulate a roll, how do you determine what the result of the roll is?
What array should you track those results in and how big should it be?
How do you track the results in such a way that you can make a histogram later?
What, if anything, besides the results do you need to store?
Think this all over, do the "experiment" manually, and then get back to us with what changes you've made to your program and what new questions you may have.

You're declaring diceAr to be size 'dice', but then indexing it with a variable which goes up to 'simDice', which = dice * 6.

Related

How do I generate multiple random variables in Java?

I am making a game where the user gets to pick the number of die for each roll. Right now my code is processing the users input correctly, but it only randomly generates the last number, the other numbers are 0. (For example if the user input 4 the roll would appear : [0,0,0,3]
Does anyone know how to get all the numbers to generate random numbers?
Here is my main:
public class game
{
public static void main(String[] args)
{
int play = 1, sum = 0;
int[] wins = new int[15];
while ((play == 1) && (sum < 15))
{
sum = 0;;
int roll = 0;
Config die= new Config();
//starts configuration
die.hand();
System.out.println("\nHere is your roll:\n");
die.get();
}
}
Here is my configure class:
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
class Config
{
public static int Dice;
int i;
public void hand()
{
System.out.println("\nLet's Configure the Game...\n");
String file = "Config.txt";
Scanner scan = new Scanner(System.in);
//configures number of dice in hand
System.out.println("Enter the number of dice you would like in your hand (1-5): ");
int hand_count = scan.nextInt();
int[] Dice = new int[hand_count];
System.out.println("Here is your roll: \n");
Random random= new Random();
for (i = 0; i<hand_count - 1; i++);
{
Dice[i] = random.nextInt(6) + 1;
System.out.println(Arrays.toString(Dice));
}
System.out.println("\nNow lets play the game...\n");
//s.close();
}
public int get()
{
return Dice;
}
}
for (i = 0; i<hand_count - 1; i++);
{
Dice[i] = random.nextInt(6) + 1;
System.out.println(Arrays.toString(Dice));
}
You have a semi-colon at the end of the first line of this for loop, resulting in your loop having no contents. Get rid of the semi-colon, and move your opening curly brace onto the same line as the for loop, i.e.
for (i = 0; i<hand_count - 1; i++) {
// do cool stuff
}
The answer by sunrise is good. But I suggest using ThreadLocalRandom instead of java.util.Random. Plus, your code has other issues to resolve.
ThreadLocalRandom
Using the ThreadLocalRandom class is thread-safe in case you ever use background threads. And a single random-number generator per thread is established, available automatically for re-use, so less overhead for repeated use.
Like java.util.Random, ThreadLocalRandom offers some nifty methods for generating a series of numbers as a stream for use in modern Java. We can shorten the code to a single-line.
int countDice = 3;
// Bounds of random number are inclusive, exclusive. So (1,7) for six-sided dice.
int[] results = ThreadLocalRandom.current().ints( countDice , 1 , 7 ).toArray();
System.out.println( "results = " + Arrays.toString( results ) );
When run:
results = [4, 6, 4]
Other issues
Variable names should start in lowercase. So public static int Dice; should be public static int dice;.
Class names start in uppercase, by convention. So public class game should be public class Game.
Your class design is disorganized. A key goal of object-oriented programming (OOP) is to more clearly model the entities being represented within your app. So I suggest you create a Die class to represent each die. That class should have a roll method that generates a new value.
In another class, instantiate some of these Die objects. Collect those instances in a collection named dice. Then for each round of your game, call roll on each die.
I was tempted to write more code for you, but this is obviously homework I'll go no further.

Identifying two random sequences in Java

I'm writing a program that flips a coin and then outputs whether the result is heads (H) or tails (T):
import java.util.Random;
public class coin {
public static void main (String [] arg) {
Random r = new Random();
int flip = r.nextInt(2);
if (flip == 1) {
System.out.print("H");
} else {
System.out.print("T");
}
}
}
Next, I would like the program to continue flipping the coin until it flips 3 heads in a row.
So for instances, I want it to output the following which stops after it identifies 3 heads:
H T T H T H T H H H
I'm having issues figuring out how to get Java to continue flipping the coins. I've tried implementing a for-loop which let me flip the coin a fixed amount of times, but I would rather that the program figures out how many times the coin is flip by itself. I suspect it should be with a while-loop but I can't seem to figure out how that would be implemented. Any help would be appreciated.
Use a counter to keep track of how many heads have been flipped and loop until 3 heads have been flipped:
Random r = new Random();
int counter = 0;
while(counter <3)
{
int flip = r.nextInt(2);
if (flip == 1) {
System.out.print("H");
counter++;
} else {
System.out.print("T");
counter = 0;
}
}
Somehing like this:
int headsInRow=0;
while(headsInRow<3){
int flip=doFlip();
if(heads)headsInRow++;
else headsInRow=0;
}
ofc it is a pseudocode but you should get the idea.

java:Adopting in algorithm?

Birthday probability problem
here is the algorithm which i follow, bit i still face problem. The algorithm is
To simplify the problem, we make the assumption that each day of the year (except February 29) is equally likely for a birthday. We will only consider 365 days in a year.
When generating a random birthday for a person, generate a random integer in the range 0-364, each number will represent an individual day in a year (0 for January 1st, and 364 for December 31st). We will use zero-based numbers to match array indexing.
When performing a single simulation, remember you only need to find one pair of matching birthdays to make the simulation count. That is, as soon as you determine that two people have the same birthday you can stop the current simulation and start the next simulation.
To ensure that everyone’s program behaves the same (so that we can auto-grade everyone’s submission), you will need to create a new Random object for each simulation run, and you will need to seed the Random object with the number of the run you are simulating (the first simulation run will use the integer 1 as the seed, the second run will use 2, etc.). You need to create a new Random object per simulation run, not per random number needed [do not use the Math.random() method in this program].
During one simulation, you will need to keep track of the days which ``correspond to someone’s birthday, or alternatively keep track of the number of birthdays that occur on any given day. There are several structures that we studied in this module of the MOOC that could be used to easily solve this problem. You are free to pick the structure of your choice. Note that the goal is to simply determine if two birthdays land on the same date.
When returning the final result, return the percentage in the range 0.0 – 100.0.
enter code here
import java.util.HashSet;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
public class Logic {
public static void process(int size, int count)
{
int number = 0;
Set<Integer> bdays = new HashSet<>();
int x[] = new int[size];
Random random = new Random();
random.setSeed(1);
int matches = 0;
boolean out = false;
for (int i = 0; i < count; i++) {
for (int j = 0; j < size; j++) {
number=(random.nextInt(365)+1);
}
for (int j = 0; j < count; j++) {
if (bdays.contains(number)) {
matches++;
}
else
{ bdays.add(number);
out = true;
break;}
if (out) {
out = false;
break;
}
}
}
double prob = 100*(double) matches / count;
System.out.println("The probability for two students to share a birthday is " + prob + ".");
}
public static void main(String[] args) {
Scanner inp = new Scanner(System. in );
System.out.println("How many students?");
int num = inp.nextInt();
System.out.println("How many times?");
int times = inp.nextInt();
process(num,times);
}
}
I suspect there are a few things wrong, but here's the first one: You're always adding number to bdays as soon as you assign number. You then later check to see if number is in bdays, which of course it will be - thus why you get the 100% match rate. What you need to do is:
Pick number
Check if number is already in bdays, and increment the counter if it is
Add number to bdays

Taking the average of an Array

I'm trying to put together a java program to do the following:
Prompt for and read in a number of integers to read
Create an array that can hold that many integers
Use a loop to read in integer values to fill the array
Calculate the average value in the array (as an integer)
This is what I have so far (although I'm pretty sure this is wrong):
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
//I don't know if I should use a while loop here or what the arguments should be
}
What should the conditions be, in order to set up the loop?
Let's look at what you need to calculate an average and what you have right now.
What you need
The total number of values
The values
Somewhere to keep the sum of values
What you have
The total number of values
A source from which to get new values
Now, from your code, you don't seem to have a place to add all your numbers. That's easy to fix; you know how to declare a new variable.
You also don't have the values, but you do have somewhere you can get them from. Since you also know how many numbers you need to sum up, you can use a loop to get that many numbers from your source.
All in all, you'll want your loop to run f times. In that loop, you'll want to get new a new number and add it to the rest. At the end, you should be able to derive the average from all that.
The better idea would be to prompt the user to enter all of the values at once, separated by spaces. IE
2 4 1 1 6 4 2 1
You can then call the split() function for Strings to split this into an array of Strings, then use the Integer.parseInt() function to turn this array of Strings into an array of ints.
Once you have your array of ints, it's a simple for loop to add all of the values together and divide by that array's length.
You can put a while loop or a for loop to input the numbers. Along with the input, keep taking the sum of the numbers. Since you have total number of values:
Average= (sum of numbers)/ total numbers.
I will write pseudo code so that it will force you to search more:
//Pseudo code starts after your array declaration
for loop from 0 to f
store it in values Array
save sum of numbers: sum= sum+values[i]
loop ends
calculate Average
public static void Average (Scanner keyboard)
{
System.out.println("Please insert number of integers to read in: ");
keyboard = new Scanner(System.in);
int f = keyboard.nextInt();
int value[]= new int[f];
double avg = 0;
for (int i = 0; i < f; i++)
{
value[i] = keyboard.nextInt();
avg += value[i];
}
avg /= f;
System.out.println("Average is " + avg);
}
I dont see a point of having array value. Or do you want some other kind of average ?
I wrote(with a friend) a code that calculates the average number:
package dingen;
import java.util.Scanner;
public class Gemiddelde {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
float maxCount = 0;
float avgCount = 0;
System.out.println("How many numbers do you want");
int n = sc.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("Number: ");
float number = sc.nextInt();
maxCount = maxCount + number;
}
avgCount = maxCount / n;
System.out.println("maxCount = " + maxCount);
System.out.println("avgCount = " + avgCount);
}
}
the only thing you have to do is replace your class and package.
you wil get the message: How many numbers do you want?:
and then it wil ask you the amount of numbers you inserted.
example:
How many numbers do you want?:6
Number:6
Number:7
Number:8
Number:9
Number:93
Number:94
maxCount = 217.0
avgCount = 36.166668
I have hoped I helped you with your problem :)

Regarding Dice Array Program

-- I am to write a program that prompts for N which is number of dice to roll and M for number of times to roll. I must repeat M times N6 or six sided die and compute and record the total sum of rolls. Using an array i must report how many times along with a percentage each possible total from 6 to 6N occurred.
Here is my code so far, i cannot get it to compile, and i think im going about it completely wrong, we only have one professor that teaches java, and he is not good at explaining things and always seems to be in a hurry if we ask questions. This is my second division class, and i learned barely anything the first semester.
////////////////////////////////
import java.util.Random;
import java.util.Scanner;
public class Lab1
{
public static Scanner in = new Scanner (System.in);
public static void main (String[] args)
{
int dice = 0;
int roll = 0;
while (true)
{
System.out.print ("How many dice do you roll?");
dice = in.nextInt();
}
System.out.print ("How many Times do you want to roll?");
roll = in.nextInt();
}
int dicetotal = Dicecount (dice); //Error message. dice cannot be resolved to Variable//
for (int i = 0; i< roll; i++)
System.out.println (Dicecount (dice));
}
}
public static int Dicecount ( int dice);
{
int dicetotal = 0;
for (int x = 0: x < dice; x++)
{
int rollcount = (int) (1+6* (Math.random()));
dicetotal+=rollcount;}
return dicetotal;
}
}
Properly format your code. This will help you find that the 6 lines starting with:
int dicetotal = Dicecount (dice);
Are not within a function block, and need to be.
You also have a colon instead of a semi-colon in this line (~7th from the bottom):
for(int x = 0; x < dice; x++){
Fixing these errors will allow your code to successfully compile - but that doesn't mean that it will do what you want it to do. Since this is homework, you'll be expected to find these issues and at least do initial troubleshooting on them yourself.
Two other problems this code appears to have:
1) In Java method names should always start with a lower-case letter. Here you have a method called dicecount. This is an invalid name and will confuse the Java compiler.
2) On the line where you declare the Dicecount method, you have a semicolon right at the end. This is a syntax error and will cause your code not to compile or behave incorrectly. The reason for this is that the semicolon is essentially telling the compiler that the current line is a complete statement. But it isn't finished, you still need to declare the body of the method.
So my advice is to change this line public static int Dicecount ( int dice); to read like this public static int dicecount(int dice). That is, remove the leading capital letter, and get rid of the semicolon at the end.

Categories