Java arraylist throwing dice - java

I'm new to Java and i'm trying to make a arraylist.
I made a small program that asks the user for a amount of dices to roll :
System.out.println("How many dices do you want to throw?");
int diceAmount = input.nextInt();
then I made a loop to print the dices but I can't get it to make the amount of dices to be random. I have to count the total dices with the random results also:
for (int i = 1; i <= diceAmount; i++) {
System.out.print(i + "-");

Random rand = new Random();
(int i = 1; i <= diceAmount; i++) {
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
System.out.print(i + "-" + roll1);
}
UPDATE:
Here is the way to sum up the numbers. So let's say you roll 2 dice every time.
Random rand = new Random();
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println("You got " + sum + ". Not bad!");

For each die roll you want a random number (presumably 1-6, if its a traditional die). So your loop is correct, but the body of the loop needs fixing:
for(int i = 0; i < diceAmount; i++){ //repeats diceAmount times
//Do loop stuff.
}
To get a random number, start with Math.random(). This will return a random double in the range [0 .. 1). This means that 0 is a valid return, but 1 is not. From there we want to stretch the range to go up to 6.
Math.random() * 6
Returns a random double in the range [0 ..6). We need integers, not doubles, so let's cast that.
(int)(Math.random() * 6)
Returns a random int in the range [0 .. 6) -> [0 .. 5]. From there, just add 1.
(int)(Math.random() * 6) + 1
Will return a random int in the range [1 .. 6], which is precisely your goal. So all together:
for(int i = 0; i < diceAmount; i++){
int dieRoll = (int)(Math.random() * 6) + 1;
System.out.println(dieRoll);
}

Use Math.random() to randomise your number of dice. There are lots of overloaded version of random() method. Read about Java.Math in Oracle documentation.

Related

JAVA Code that checks for duplicates doesn't work

I am learning how to code and my teacher gave me an exercise to create a lottery program that generates 6 random numbers between 1 and 49 with no duplicates and one bonus number that could be a duplicate. My program generates all the numbers fine, but for some reason duplicates still appear. Could someone please explain why the code that checks for duplicates doesn't work, as I have been struggling to understand why it doesn't work. Please bear in mind that I'm a new programmer so try and keep explanations beginner friendly. Thanks in advance.
int[] lottonums = new int[6];
//Generates 6 random numbers between 1-49
for(int i = 0; i < lottonums.length; i++){
lottonums[i] = (int)(Math.random()* 49 +1);
}
//Checks for duplicates
for(int x = 0; x < 6; x ++){
for(int y = x + 1; y < 6; y ++){
while(lottonums[x] == lottonums[y]){
lottonums[y] = (int)(Math.floor(Math.random() * 49 + 1));
}
}
}
//Bonus ball, no checks for duplicates
int bonusBall = (int)(Math.random() * 49 + 1);
Arrays.sort(lottonums);
System.out.println("\nThe lottery numbers are: ");
for( int nu = 0; nu < lottonums.length; nu ++){
System.out.print(lottonums[nu] + " " );
}
System.out.println("\nThe bonus number is: " + bonusBall + "\n");
Best Way to have unique number is by using Set instead of array.
if you are not aware much about set have a look into it set TreeSet
Basically if you look at your code
//Checks for duplicates
for(int x = 0; x < 6; x ++){
for(int y = x + 1; y < 6; y ++){
while(lottonums[x] == lottonums[y]){
//below line does not gurrantee its going to insert unique number
//example [1,2,6,6] here at index 2 and 3 6 is there
//now you got this while checking duplicate
//after you are generating new random suppose new generated number is 2
// as you are not going back to check duplicate so it will be inserted
lottonums[y] = (int)(Math.floor(Math.random() * 49 + 1));
}
}
}
you can try the below solution using set
which fits yous requirement
// TreeSet will have unique element in sorted manner no need to sort again
TreeSet<Integer> set=new TreeSet<>();
int n=6;
while(set.size()<n-1)
{
set.add((int)(Math.random()* 49 +1));
}
//Bonus ball, no checks for duplicates
int bonusBall = (int)(Math.random() * 49 + 1);
System.out.println("\nThe lottery numbers are: ");
for( int nu :set){
System.out.print(nu + " " );
}
System.out.println("\nThe bonus number is: " + bonusBall + "\n");
}

Calculate Average of Previous Loop - Java

So, I am working on this code for my AP Computer Science class, and I ran into a problem.
First, here is my code:
//loop counters
int counterOne = 0;
int counterElse = 0;
int loop = 1;
int iNum = 1000;
//create file
PrintWriter outFile = new PrintWriter(new File("newFile.txt"));
for (int counter = 1; counter <= iNum; counter++)
{
while (loop >= 1)
{
Random rand = new Random();
int iRand = rand.nextInt(5)+1;
if (iRand != 1)
{
counterElse++;
loop++;
}//end of if of if-else
else
{
counterOne++;
loop = 0;
}//end of else of if-else
}//end of while loop
int tries = counterElse+counterOne;
//int average = (tries + prevTriesSum) / counter
System.out.println("It took " + tries + " try/tries to win!");
//outFile.println("It tool an average of " + average + " tries to win.");
}//end of for loop
How do I calculate the average of the trials? As you can see from the end of my code, I commented out a line that I would want to calculate the average. This is because I don't know how to calculate prevTriesSum, which represents the sum of all of the other trials. Here is an example: Assume the loop runs six times, and with the first run, it takes 3 tries, 5 on the second run, 7 on the third, 11 on the fourth, 2 on the fifth, and 4 on the sixth (the most recent one. now tries = 4).
I would want prevTriesSum to equal 3 + 5 + 7 + 11 + 2 + 4.
How do I get the program to calculate that?
Your average is computed in integer arithmetic which means any fractional part is discarded. Consider using a floating point type for the average, and prefix the right hand side of the assignment with 1.0 * to force the calculation to occur in floating point.
You must not reinitialise the random generator in the loop, else you ruin its statistical properties. Do it once before you enter the loop.
Before the while loop, add
int prevTriesSum = 0;
Replace your commented int average = line with
prevTriesSum += tries;
And after the for loop add
double average = (prevTriesSum + 0.0) / counter;
outFile.println("It tool an average of " + average + " tries to win.");
As for the random number generator, Bathsheba is correct. You must move that above the for loop. Just move the declaration.
You'll also need to change your for loop slightly. As it stands, it will equal 1001 when the for loop terminates. Change it as follows:
for (int counter = 0; counter < iNum; counter++)
This will ensure that your average calculation is correct.

Working with random integers

Here is the assignment:
For this program, there are two "parts". The first part will run the trials and determine how many caps each trial opens before finding a winning cap. Every trial (person) will be a winner. The number of caps opened by each trial is written to the file.
The second part of the program will read in the values and calculate the average. The average should be between 4.5 and 5.5 since there is a 1 in 5 chance of winning.
It compiles and runs, but the average is always 0.
My code:
int randNum = 0;
Random randNumList = new Random();
int counter = 0;
Scanner in = new Scanner(System.in);
System.out.println("How many trials will there be?");
int trials = in.nextInt();
int winner = 0;
PrintWriter outFile = new PrintWriter (new File("cap.txt"));
//run trials
for (int loop = 1; loop <= trials; loop++)
{
//select random number until 5 is selected
randNum = randNumList.nextInt(6);
for (randNum = randNumList.nextInt(6); randNum == 5; randNum++)
{
randNum = randNumList.nextInt(6);
counter++;
}
outFile.println(loop + " " + randNum);
}
outFile.close ( ); //close the file when finished
String token = " ";
Scanner inFile = new Scanner(new File("cap.txt"));
while (inFile.hasNext())
{
token = inFile.next();
if(token.equals("5"))
winner++;
}
double average = winner/counter;
System.out.println("The average number is " + average);
Apart from the int/int division accuracy problem which should be winner/(double)counter or (double)winner/counter try changing your inner for loop to a do while. In general, prefer while when you don't know the exact number of iterations.
Also, randNumList.nextInt(6) is [0-5], thus there are 6 possible outcomes -> there is a 1 in 6 chance of winning. To correct this, use randNumList.nextInt(5) + 1
for (int loop = 1; loop <= trials; loop++) {
//select random number until 5 is selected
do {
randNum = randNumList.nextInt(5) + 1;
counter++;
} while (randNum != 5);
outFile.println(loop + " " + randNum); //why here?? maybe you should add it below counter++;
}
also if(token.equals("5")) won't work, as you write (loop + randNum), it should work if you use outFile.println(randNum);
Your cap.txt file doesn't contain "5" => winner = 0 and average = 0/counter = 0 (always).
winner/counter returns an int not a double (integer division because both operands are integer so the result is truncated). Try this:
winner/(double)counter
That does return a double.

How to create random number between 2 numbers but it just change in a range?

Anybody know how to create random number between 2 numbers but it just change in a range ?
For instance, create random number between 10 - 100, with the change every time is in range [-5,+5].
Ex: if the first random is 17, the after random number will be in range [12, 22]
Thank you!
This algorithm picks an initial random value x, in range [0, 100]. After that every new random value y will be within 5 of the previous random value x.
int maximum = 100;
int minimum = 0;
Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum = rn.nextInt(range) + minimum;
System.out.println(randomNum);
for (int i=0; i< 100; i++) {
maximum = randomNum + 5;
minimum = randomNum - 5;
range = maximum - minimum + 1;
randomNum = rn.nextInt(range) + minimum;
System.out.println(randomNum);
}
I think i understand your question, but little bit confused with your sequence on example. This is one of the possible answer:
In java, you can generate like that:
Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum = rn.nextInt(range) + minimum;

how to create Random numbers [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 9 years ago.
how would I create up to 15-20 random numbers between 100-200 in java?
I have this atm but it creates any random numbers but I want the numbers to be between 100 and 200 but I don't know how I would go about adding this to the code below. please can someone help.
Random rand = new Random();
int Randnum;
for(int i = 0; i <=20; i++) {
System.out.println(Randnum + " ");
}
}
This has been answered before, but use rand.nextInt(int n). This will generate a number between 0 (inclusive) and n (exclusive). In your case, use rand.nextInt(101)+100 to generate a number between (and including) 100 and 200.
Random rand = new Random();
int Randnum;
for(int i = 0; i <=20; i++) {
Randnum = rand.nextInt(101)+100;
System.out.println(Randnum + " ");
}
}
Random rand = new Random();
int Randnum;
for (int i = 0; i <= 20; i++) {
Randnum =rand.nextInt(101) + 100;
System.out.println(Randnum + " ");
}
nextInt(n) method of Random class returns a number between 0(inclusive) and n(exclusive).
In your case, you need a number between 100 and 200, so fetch a number using nextInt with values ranging from 0 to 101 (you get numbers from 0 to 100) and add 100 to it to get numbers from 100 to 200.
You can either use Random or Math#random
use Math.random()
You can do something like:
int[] randnum = new int[20];
for(int i = 0; i <20; i++)
{
randnum[i] = (int)((Math.random() * 101)+100) ;
}
now you have 20 integers between 100 and 200.

Categories