Dice simulation finding the right dots - java

how many dice dots do u want?
6
try 1 : 2
try 2 : 4
try 3 : 5
try 4 : 6
In 4 try's u found 6 dots
So this is what I'm trying to get as output, but can't seem to find how.
System.out.println("how many dice dots do u want?");
int dots = s.nextInt();
int dots2 = (int) (6 * Math.random()) + 1;
This is what I have. I tried a for loop now, but it doesn't seem to work. Can someone help me?

You can achieve what you want this way:
Scanner scan = new Scanner (System.in);
int randomValue = 0; //this is the random value that'd be autogenerated in each loop
int counter = 1; //this represents the number of trials
System.out.println("how many dice dots do u want?");
int dotsWanted = scan.nextInt();
while(randomValue != dotsWanted){
randomValue = (int) (6 * Math.random()) + 1;
counter++;
}
System.out.printf("In %d trials, %d dots were found\n", counter, dotsWanted);
I hope this helps.. Merry coding!

Please, format your question properly next time, it helps us to help you :)
You need a while loop to throw the dice.
int dots = s.nextInt();
boolean found = false;
Random rnd = new Random();
while(!found) {
int rolled= rnd.nextInt(6) + 1;
if(rolled == dots) // do your stuff
found = true;
}
Hope it helps.

Related

Extracting a number in Java isn't working as expected

This program is supposed to print the numbers (indiviual digits) in a number
`
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int number = sc.nextInt();
int Size = 0;
String Conversion = Integer.toString(number);
Size = Conversion.length();
int n = 0;
while (n <= Size){
int d = number%10;
int power = Size - 2;
number = (number/(10^(power)));
System.out.println(d);
n += 1;
}
}
}
`
Really Appreciate for Anyone for Took time to help me.
Thanks
For some reason I get
1
9
3.
instead of
1
3
4
using the debugger gives me some hint, Specifically this block `
number = (number/(10^(power)));
`
for second iteration the value is +4 than expected, 3.
for third Its okay.
changing and adding +4 on that block gives
1
3
7
4
Found it !!
Credit OH GOD SPIDERS, tkausl
Solution 1 : Instead of using carrot characters in
number = (number/(10^(power)));
use Math.pow function.
Solution 2 :
Don't use (number/(10^(power))
instead just divide by 10

My Birthday Problem code is not printing anything

I am an absolute beginner to learning programming and I was given this assignment:
Birthday problem. Suppose that people enter a room one at a time. How people must enter until two share a birthday? Counterintuitively, after 23 people enter the room, there is approximately a 50ā€“50 chance that two share a birthday. This phenomenon is known as the birthday problem or birthday paradox.
Write a program Birthday.java that takes two integer command-line arguments n and trials and performs the following experiment, trials times:
Choose a birthday for the next person, uniformly at random between 0 and nāˆ’1.
Have that person enter the room.
If that person shares a birthday with someone else in the room, stop; otherwise repeat.
In each experiment, count the number of people that enter the room. Print a table that summarizes the results (the count i, the number of times that exactly i people enter the room, and the fraction of times that i or fewer people enter the room) for each possible value of i from 1 until the fraction reaches (or exceeds) 50%.
For more information on the assignment
However, my code won't print. I would really appreciate if someone could help me find the problem to my assignment.
public class Birthday {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]); //number of days
int trials = Integer.parseInt(args[1]);
boolean[] birthdays = new boolean[n];
int[] times = new int[n + 2]; //number of times i people entered the room
int r;
for (int t = 1; t <= trials; t++) {
for (int k = 0; k < n; k++) { //reset birthday
birthdays[k] = false;
}
for (int i = 1; i <= n; i++) { //number of times
r = (int) (Math.random() * (n - 1)); //random birthday
if (birthdays[r] = false) {
birthdays[r] = true;
continue;
}
else if (birthdays[r] = true) {
times[i]++; //number of times i people entered the room + 1
break;
}
}
}
int j = 1;
while ((double) times[j] / trials <= 0.5) {
System.out.print(j + "\t" + times[j] + "\t" + ((double) times[j] / trials));
j++;
System.out.println("");
}
}
}
I can spot two errors from your code
As Scary Wombat pointed out, you are miss double equal sign inside of your if statement.
The assignment is asking you to calculate "fraction of times that i or fewer people enter the room", meaning you need to do a summation for the first i indices and divided by trials.
For example, among 1 million trials, the fraction in which first duplicate birthday happens when 4th person enters is
(times[0] + times[1] + times[2] + times[3])/ 1000000
Here is what I got:
1 0 0.0
2 2810 0.00281
3 5428 0.008238
4 8175 0.016413
As you can see the fraction is calculated by adding the first three elements together and then divided by 1000000 (2810 + 5428 + 8175 = 16413) / 1000000 = 0.016413
The way you are calculating the fraction ((double) times[j] / trials) is not correct.
You are not adding the previous counts as shown in the example. To do so, you can create a new variable to store the sums of previous counts. and use it as your while loop condition. For instance, see below..
csum += times[j]; // this adds the previous counts into a cumulative sum.
This cumulative sum is supposed to be the one u use to divide by trials to get your probability. Cheers!

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.

Equal Spacing In print statements

So I was just about finished with a small little program and when I ran it everything worked fine. I did have 1 small technical issue that I didnt like and it was an unevenly spaced "table" if you would. In a nutshell I want it so my outputs are aligned on both sides.
Original output:
How many numbers should be generated?
10
What is the number of values of each random draw?
1000
- 1 108
- 2 90
- 3 101
- 4 98
- 5 117
- 6 97
- 7 89
- 8 111
- 9 93
- 10 96
Code:
import java.util.Random;
import java.util.Scanner;
public class tester
{
public static void main(String[] args)
{
Random rnum = new Random();
Scanner in = new Scanner(System.in);
int x = 0;
int y = 0;
int num = 0;
int length = 0;
System.out.println("How many numbers should be generated?");
x = in.nextInt();
System.out.println("What is the number of values of each random draw?");
y = in.nextInt();
int[] roll = new int[x];
for(int i = 1; i<=y; i++){
num = rnum.nextInt(x);
roll[num] = roll[num] + 1;
}
length = (int) Math.log10(x) + 1;
for(int i = 0; i < x; i++){
System.out.println(i+1 + " " + roll[i]); //This is the code that prints the original output
/*
* This is the code I attempted that did not give the desired result
* a = i;
System.out.println(i+1);
while(Math.log10(i) < length){
System.out.print(" ");
length--;
}
System.out.print(roll[i]);*/
}
}
}
Take a look at the System.out.format (https://docs.oracle.com/javase/tutorial/essential/io/formatting.html) and in perticular the width option. This is probably what you are wanting.
Two ways to go about this:
1) As stated already, look at the System.out.format directory. It has a wide availability of methods to format your output
2) Change the spacing in a manual way, where the spacing depends on the amount of characters in the number to the left.

Array guessing game

I'm a java noob and for a class assignment I had to create a guessing game. I have not finished the game yet but I want some advice when it comes to simplifying my array for the keyboard input. I was able to create the array for a random "5" digit number but I don't know how to simplify the array for keyboard input in the same manner for the random numbers.
Here is the part that i need advice on:
Scanner input = new Scanner(System.in);
Random number = new Random();
int x,y,z,a,b;
x=number.nextInt(9); //The 9 limits the randomized number to values between between -1 & 10
y=number.nextInt(9);
z=number.nextInt(9);
a=number.nextInt(9);
b=number.nextInt(9);
int secretNum[] = {x,y,z,a,b};
int numOfGuess = 3;
boolean win = false;
System.out.println("Try to guess the five digit number");
{
while (win || numOfGuess > 0)
{
int guess[]=new int[5];
guess[0]=input.nextInt(9);
guess[1]=input.nextInt(9);
guess[2]=input.nextInt(9);
guess[3]=input.nextInt(9);
guess[4]=input.nextInt(9);
numOfGuess--;
First, you can simplify the number generation from your complicated method to simply:
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
If you set max = 99999 and min = 10000, it will give you a random 5 digit number.
For accepting user input, you're far better of using
Scanner scan = new Scanner(System.in);
guess = scan.nextLine();
Then use an if statement to see if the number is within the 5 digit constraints.
In terms of the loop, the comment suggested using a for loop instead of a while loop. It would be far better imo to follow his advice. i.e.
for (int i=0;i<maxGuesses;i++)
Listen for input
If correct, set won=1 break
else do nothing
end for loop
if won=1 Print you won
Else print You suck at guessing 5 digit numbers
Simple code is usually the best way to go:
In pseudocode:
secret = 10000 + number.nextInt(90000);
for (int i = 0; i < numOfGuess; i++) {
read guess (a single int)
if guess == secret then user wins (and exit)
}
user loses

Categories