Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
The following is a lab more my Intro to Java class. It's my first Java class and I'm beyond stuck. I have a few lines of code but nothing noteworthy.
Solve below problem using ‘do-while’ and random number generator.
Simulate rolling a pair of dice 10,000 times and counts the number of times doubles of are rolled for each different pair of doubles.
Your program should roll two dice using the Random object (that is, generate two numbers between 1 and 6)
Define 6 counters variables
If the dice match (both should be same 1-1, 2-2, 3-3...), then increment a specific counter [you can use ‘if’ or ‘switch’ for condition check (dice1==dice2) and counter increment.
Display the results after the loop completes 10,000 times.
1-1 displayed: 30 times
2-2 displayed: 100 times
...................
6-6 displayed: 890 times
Code:
public class DiceRoll {
public static void main(String []args){
int x = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
do {
int dice1 = (int)(Math.random()*6)-1;
int dice2 = (int)(Math.random()*6)-1;
if (dice1 == dice2){
if (dice1 == 1){
counter1++;
}
if (dice1 == 2){
counter2++;
}
if (dice1 == 3){
counter3++;
}
if (dice1 == 4){
counter4++;
}
if (dice1 == 5){
counter5++;
}
if (dice1 == 6){
counter6++;
}
}
} while (x > 10000);
System.out.println("Results:");
System.out.println(" ");
System.out.println("1-1 displayed: " + counter1);
System.out.println("2-2 displayed: " + counter2);
System.out.println("3-3 displayed: " + counter3);
System.out.println("4-4 displayed: " + counter4);
System.out.println("5-5 displayed: " + counter5);
System.out.println("6-6 displayed: " + counter6);
}
}
Okay, I don't want to just give a solution, so I am going to attempt to walk you through it. (Sorry if I tell you something you already know)
1. The Random object. This is an instance of the Random class. You need to create a variable of type random and assign it to a Random object.
Random dice = new Random();
Do this outside of the do-while loop, so that you aren't generating a new instance of Random and assigning the dice variable to that each time.
2. You are then going to need to generate random numbers using this object. If you look in the documentation you will find one method that returns an int within a user specified range:
nextInt(int bound)
To generate a random number, call this off of dice and store the return in another variable:
int rollOne = dice.nextInt(6)+1;
The reason you are adding 1 to the answer is that nextInt returns a value between zero and the given value exclusive.
3. The do-while loop. This loop executes once, then checks the conditional after the while keyword before every subsequent execution (to see if it should execute again).
You need the loop to execute 10,000 times.
int rolls = 0
do {
rolls++; // Increments rolls by one
} while(rolls < 10,000); //It starts at one, so this will loop 10,000 times
4. What to put in the loop: Every iteration, you need to roll the dice twice (use nextInt twice), compare their values, and increment the appropriate counter.
Okay, now that I have seen your code, your problem is simple:
You need to increment x in the loop, perhaps right after the
do {
line. You also need to edit the conditional in the while part. It should be
} while (x < 10000); //Less than, not greater than >
Related
This is my first time using stack overflow, so I'm so sorry if this is formatted incorrectly in any way. For a comp sci project, I have to do some different things to a 40-item Array List of random numbers.
The task I'm struggling with is this:
Count the longest run of the same number. A run continues only when consecutive numbers
have the same value. The repeated number and the length of the run is then printed. (Ex: Longest run is of number: 3, length is: 5.)
If there is more than one run of maximum length, mark the last one. Print the array with the longest run marked in the following fashion:
1 1 1 6 5 4 6 3 2 3 2 (3 3 3 3 3) 1 5 6 3 4 4 4
I genuinely have no idea how to approach this problem. Even just some pseudocode could be helpful; I know that these should probably be 2 different 'for' loops, one that detects the run and the other that prints it. I have some code from a friend who completed this using Arrays instead of ArrayLists:
public String longestRun()
{
int maxRun=1;
int currentLen = 1;
int repeated = x[0];
for (int i =1; i< 40-1; i++)
{
if (x[i] == x[i+1])
currentLen++;
else
{
if (currentLen >= maxRun)
{
maxRun = currentLen;
repeated = x[i-1];
startRun = i-maxRun;
endRun = i-1;
}
currentLen = 1;
}
}
return "The longest run is " + maxRun + " and the repeated number is " + repeated ;
}
public String printParenth()
{
for(int i = 0; i<40; i++)
{
if(i != startRun+1 && i != endRun+1)
System.out.print(x[i]);
else if(i == startRun+1)
System.out.print("(" + x[i]);
else
System.out.print(x[i] + ")");
}
return "";
}
I know how to create the ArrayList, convert to string & print, etc, it's just this one task that I don't understand. I assume this should be easier with an ArrayList, considering the increased number and utility of ArrayList methods. Thanks so much in advance, I really appreciate it!
Put your numbers in a list or an array.
Set max to 1 (you will always have at least 1 number).
initialize count to 1.
initialize the variable most to the first number in the array
also set the variable last to the first number in the array.
Now iterate thru the list starting with the second number.
If the current number is the same as last, increment count.
then see if count > max.
if it is
set max = count.
set most = last
if it isn't
set count = 1
set last = current number
continue in this fashion until all numbers have been checked.
At the end most will contain the number that was repeated and max will contain the length of the repetition.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I need to exit the following code without using break otherwise my professor will give me a 0. What is the most efficient way? Sorry, I am a noob. Please help. Basically, he wants the program to exit logically. Thats exactly what he said. Also, why do people not like break? I mean the program works perfectly with break.
//********Import statements*******//
import java.util.Random;
import java.util.Arrays;
public class randomNumbers
{
public static void main(String[] args)
{
//***********Initialize variables************//
Random rand = new Random();
int[] numbers = new int[10]; //Initialize array
//**********************************************************************************//
//For loop generates 10 Random Numbers in the range 1 - 23
for(int i = 0; i < numbers.length; i++)
{
//Generate random numbers between 1-23
int randomNum = rand.nextInt((23-1)+ 1) + 1;
//if number generated is less than 20
if(randomNum < 20)
{
//number generated is part of numbers to be outputted
numbers[i] = randomNum;
}
else //else statement, quit program as number is greater than 20
{
break;
} //end if
}//end for loop
//Display output
System.out.println("Numbers Generated: " + Arrays.toString(numbers));
//**********************************************************************************//
} //end main
} //end program
Use something like a do...while
int randomNum = ???
do {
randomNum = ???
} while ( randomNum < 20 );
System.out.println("Random was >= 20");
To exit a void method (any void method, including the main() method) use:
return;
i.e. replace break with return.
So the goal of the loop is to continue until a condition is met. Determine what that condition is and force the conditional to be met. In this case, make i equal to numbers.length.
Side Note
As Bohemian stated, return is another great option. This will become more relevant when methods start returning values. Return is a common way you will exit from methods with loops in them, unless the return type is void.
You can add condition to loop.
Create boolean property and check if you must finish loop.
boolean finish = false;
for(int i = 0; i < numbers.length && !finish; i++)
{
.
.
.
if(randomNum > 20){
finish = true;
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
This is my first time putting a code together for Java based on my own so i was hoping if you someone would be kind enough to review and provide feedback or constructive criticism on this code.
The goal is to roll 2 dices and 10k times. add pairs and display their frequency.
Code runs fine but maybe i am over looking some logical error or a better way to do this
/**
* Use the Random Number generator to write a java application that simulates a pair of dice.
* Throwing the pair of dice 10,000 times- Add the values for the pair
* Print the frequency at the end of 10,000 runs
* #author
*
*/
import java.util.Random;
public class diceSimulation {
public static void main(String[] args) {
/**
* Declare variables and store dice max roll in Thousand
*/
final int THOUSAND = 10000;
int counter, dice1, dice2;
//initiate an array with elements to keep count
int [] diceValue = new int [7];
// display welcome message. no other purpose but trial
welcome ();
// create new instance of random
Random rollDice = new Random();
/**
* Set counter to start from 1 and go till desired constant number
* Rolling two separate dices and storing values in dice1 & dice 2 respectively
*/
for (counter=1; counter<=THOUSAND;counter++){
dice1=rollDice.nextInt(6) + 1;
dice2=rollDice.nextInt(6) + 1;
// If statement to check if values are the same or not
if (dice1==dice2){
// IF values are same then go into for loop and store value in array element
for (int i=1; i<=6; i++){
if (dice1 == i && dice2 == i){
// add value for the number displayed into the array
diceValue [i] += 1;
}
}
}
}
// Display results totals of paired rolls
for (int a=1; a<diceValue.length; a++){
System.out.println(" You rolled set of " + a + " " + diceValue[a] + " times");
}
}
public static void welcome () {
System.out.println("welcome to dice world!");
}
}
// If statement to check if values are the same or not
if (dice1==dice2){
// IF values are same then go into for loop and store value in array element
for (int i=1; i<=6; i++){
if (dice1 == i && dice2 == i){
// add value for the number displayed into the array
diceValue [i] += 1;
}
}
}
This whole part is a little bit redundant.
After that you know that dice1==dice2 you only iterate over i to stop when it's equal to both and then you add 1 to diceValue[i] that is assured to be the same as diceValue[dice1] or diceValue[dice2].
That can be made directly by diceValue[dice1]++ (again, after knowing that dice1==dice2
What I'm attempting to do is have 2 or three do while loops that each have 10 or so if statements within that contain questions. Each if statement (question) is assigned a number (generated by random num gen) and triggers a different question. I want them to trigger randomly when the program is run- So if you run it once the 3rd question in the list might trigger first and the next time the 7th question might trigger first. A sample do while loop is below:
do {
i++;
//set what variable you want to represent random vars
randomint = randomGenerator.nextInt(10);
System.out.println(randomint);
/*
* need to generate 1 number per do loop (as opposed to 10 each loop which this is doing)
* and make sure that the numbers 1-10 are all hit within the 10 cycles of the do loop
* then will do again for a harder set of questions in the second loop
*/
if(randomint==1) {
System.out.println("What is the capital of PA?");
guess= in.nextLine();
if(answer1a.equals(guess) || answer1b.equals(guess)) {
System.out.println("Correct! Good job!");
score=score+5;
}
/*
* add another for loop that gives 4,3,2,1,0 points based on # of guesses used
*/
else {
do {
System.out.println("Nope, try again!");
guess= in.nextLine();
if (answer1a.equals(guess) || answer1b.equals(guess))
System.out.println("Correct! Good Job!");
}while (!answer1a.equals(guess) && !answer1b.equals(guess));
}
}
} while (i !=10);
So that same "if" statement will be repeated for ==2,==3, etc.. for different questions
Obviously the problem here is that every time the do loop repeats I generate a completely new set of 10 random numbers. Is there a way to generate 10 random numbers but it stops after each one and scans through my if statements so it picks one, then continues onto the second value in the random number generator? I want this to ask each individual question (10) and then exit the original do loop as determined by my i++ count.
I did try to search for this but was having trouble finding anything- It might possible be a term tat I havent come across yet. Thanks all
Use an Array to save all generated value, for the next iteration..
int[] anArray; //use this array to save all showed question
anArray = new int[10];
int i = 0;
//set what variable you want to represent random vars
randomint = randomGenerator.nextInt(10);
do{
if(i > 0){
//if there is min. 1 value in the array check if the next
//random value was already in the array
while(Arrays.asList(anArray).contains(randomint) == true){
randomint = randomGenerator.nextInt(10);
}
}
anArray[i] = randomint; //save the new value for the next checking
i++;
System.out.println(randomint);
//the Question if statements goes here...
}while (i !=10);
OR, you can use Shuffle to shuffle the array ordering, see code below:
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
Prior to your do-while loop, create an ArrayList with the ten numbers. Shuffle the ArrayList. Then change your do-while to an iterator loop over the shuffled values.
I'd also recommend using a switch statement rather than a series of ifs.
I am trying to write a method that repeatedly flips a coin until three heads in a row are seen. Each time the coin is flipped, what is seen is displayed (H for heads, T for tails). When 3 heads in a row are flipped a congratulatory message is printed.
eg.T T T H T H H H
Three heads in a row!
public static void threeHeads(){
Random rnd=new Random();
char c = (char) (rnd.nextInt(26) + 'a');
for(int i=1;i<=c.
}
I am stuck inside for loops.How should I specify the number of times it will loop.Even if I declare 3 different char c,how can I convert it to the number of times to loop.I was thinking if I should find the ascii table to find which number is H and T to print these 2 out specially?Or a loop is redundant?
public static void threeHeads(){
Random rnd=new Random();
char c = (char) (rnd.nextInt(26) + 'a');
if(c=='H' && c=='H' && c=='H'){
System.out.println("Three heads in a row!");
}
}
Another problem is assignment which is == and equals.
For a boolean value,i use ==
I understand that for strings,I should use equal.Then for a char character,what should I use?
eg.char=='y'
Am I right?
I assume this is a homework.
Instead of using Random.nextInt, use Random.nextBoolean.
Say TAIL is false and HEAD is true
You then need a counter of HEADS in a row, that is incremented when new HEAD is turned, and reset to 0 when TAIL is flipped.
Once that counter has a value of 3 you have an exit condition for your loop.
The outcome of coin flip is binary. Match H to 1 and T to 0. You only generate these two numbers randomly.
Put a counter cnt in your loop which will set to 0 when it is T (0) and cnt++ if it is H (1). Then you'll have to break out of the loop if cnt > 2 (something like if(cnt>2) break;)
Don't forget that you need to regenerate random number each time you go through the loop. In your current code it is done only once.
I think these ideas should be enough to write your code.
In general, whenever you find yourself asking "How do i keep track of XXX", the answer is to declare a new variable. In your case, however, you can use the loop counter i:
Here is how i would approach this problem:
public static void threeHeads()
{
Random rnd=new Random();
char c; //no need to initialize the char
//ostensibly, we will loop 3 times
for(int i=0; i < 3; i ++)
{
c = rnd.nextBoolean() ? 'h' : 't'; /*get random char*/;
if (c != 'h')
{
//but if we encounter a tails, reset the loop counter to -1
//that way it will be 0 next time the loop executes
i = -1;
}
System.out.println(c);
}
}
This way it will keep trying to loop three times until c is 'h' every time.
To answer your question about == versus equals():
You can always use == on primitive types (int, char, double, anything that is not an object). For objects (Strings, Double-with-a-capital D's, Lists), you are better off using equals. This is because == will test whether or not the objects are exactly the same object -- which is only true if they occupy the same location in memory. Nine times out of ten you are actually interested in checking whether or not the objects are equivalent and you don't care whether or not they are literally the same object. It is still a good idea to understand the details of this however, in case you encounter a situation where you do want to use ==.
int head =0;
int tail =1;
public static void threeHeads(){
Random rnd=new Random();
int headsSeen = 0;
while(headsSeen < 3){
int res = rnd.nextInt(1); //returns 1 or 0
if (res == head){
headsSeen ++;
}else{
headsSeen = 0; //there was a tail so reset counter
}
}
///At this point three heads seen in a row
}