I'm working on a coin flip assignment and I have the majority of it functioning properly (albeit in a less elegant fashion compared to the code I see on here).
I'm trying to find a way to tell the user which number appears most in their flips, and if heads are assigned to even #s, and tails to odd #s, which one came up the most. I'm looking for suggestions to implement these features.
Here is the code thus far:
import java.io.*;
import java.util.*;
public class coinFlip {
public static void main(String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int flips;
int anArray[];
int x;
int r;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
System.out.println("How many times would you like to flip your coin?");
flips = Integer.parseInt(in.readLine());
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
}
if(flips <= 1000) {
System.out.println("You want to flip " + flips + " times");
anArray = new int[flips];
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
if (anArray[x] == 1) {
counter1 += 1;
}
else if (anArray[x] == 2) {
counter2 += 1;
}
else if (anArray[x] == 3) {
counter3 += 1;
}
else if (anArray[x] == 4) {
counter4 += 1;
}
else if (anArray[x] == 5) {
counter5 += 1;
}
else if (anArray[x] == 6) {
counter6 += 1;
}
else if (anArray[x] == 7) {
counter7 += 1;
}
else if (anArray[x] == 8) {
counter8 += 1;
}
else if (anArray[x] == 9) {
counter9 += 1;
}
else if (anArray[x] == 10) {
counter10 += 1;
}
}
System.out.println("\n You rolled 1 " + counter1 + " times.");
System.out.println("You rolled 2 " + counter2 + " times.");
System.out.println("You rolled 3 " + counter3 + " times.");
System.out.println("You rolled 4 " + counter4 + " times.");
System.out.println("You rolled 5 " + counter5 + " times.");
System.out.println("You rolled 6 " + counter6 + " times.");
System.out.println("You rolled 7 " + counter7 + " times.");
System.out.println("You rolled 8 " + counter8 + " times.");
System.out.println("You rolled 9 " + counter9 + " times.");
System.out.println("You rolled 10 " + counter10 + " times.");
}
}
}
import java.io.*;
import java.util.Random;
public class CoinFlip {
public static void main(final String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
System.out.println("How many times would you like to flip your coin?");
final int flips = Integer.parseInt(in.readLine());;
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
return;
}
System.out.println("You want to flip " + flips + " times");
final int[] counters = new int[10],
side = new int[2];
int r=0,x,max=0;
final Random rand = new Random();
for(x = 0; x < flips; ++x) {
r = rand.nextInt(10);
System.out.println(r+1);
counters[r]++;
}
for ( x = 0; x < counters.length; ++x )
{
System.out.println("You rolled " + (x+1) + " " + counters[x] + " times.");
if ( counters[x] > max )
{
max = counters[x];
r = x+1;
}
side[x%2] += counters[x];
}
System.out.println(r + " was rolled most.");
System.out.println("You rolled " + side[0] + " heads and " + side[1] + " tails." );
}
}
Using loops, as shown in another answer, will make life much easier.
There is a more critical logic error in your code:
You round the output of Math.random(), which gives a float between 0 and 1, and round that to get an integer. The following table shows what output you'll get from your code in respect to the RNG:
| Math.random() output | Resulting Integer |
| 0 ~ 0.04999 | 0 |
| 0.05 ~ 0.14999 | 1 |
| ...... | ..... |
| 0.95 ~ 0.99999 | 10 |
See the problem? 0 and 10 appear only half as much as the other numbers.
You should either floor() the output, or use Random.nextInt() to generate a uniform distribution of ints.
This would make your life much easier:
int counter[10];
...
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
counter[r-1]++;
}
for(i=1; i <= counter.length; i++)
System.out.println("You rolled " + i + " " + counter[i-1] + " times.");
For your other two problems, there's nothing to really "suggest". Just iterate over counter, remember the largest value, and add up the even and odd indices separately.
Related
I am making a dice game, the rules are 2 dice are thrown randomly, if the sum of both dice are 7 or 11 in the first try, the user wins. if the sum is 2,3 or 12 in the first try, the user loses. if the sum is 4,5,6,8,9,10 then that sum is set as an establish point and continues to throw the dice till the sum matches the established point and the user wins, however if the establish point is 7 the user loses.
the game plays 3 times and records how many times I have won or lost. however, I am not able to get that part finished, help would be appreciated, my code is bellow.
package roll;
import java.util.Random;
public class RandomSumGame {
boolean start;
int d1;
int d2;
int sum = d1 + d2;
int valuepoint;
String plus = "+";
public void play(int d1, int d2) {
int win = 0;
int loss = 0;
sum = d1 + d2;
for (;;) {
if (sum == 2 || sum == 3 || sum == 12) {
start = false;
loss++;
System.out.println(" = " + sum + ";you lose");
break;
} else if (sum == 7 || sum == 11) {
start = true;
win++;
System.out.println(" = " + sum + ";you win ");
break;
}
valuepoint = sum;
if (valuepoint == 4 || valuepoint == 5 || valuepoint == 6 || valuepoint == 8 || valuepoint == 9
|| valuepoint == 10) {
System.out.print(" = " + valuepoint + " you establish a value point " + valuepoint + "\n");
break;
}
}
for (;;) {
if (sum == 7 || sum == 11) {
break;
} else {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
int f1 = d1;
System.out.print("\t" + "-you rolled again " + d1 + " " + plus);
for (int x = 0; x < 1; x++) {
d2 = 1 + rand.nextInt(6);
int f2 = d2;
int loda = f1 + f2;
System.out.print(" " + d2 + " = " + loda + "\n");
}
}
sum = d1 + d2;
if (sum == valuepoint) {
start = true;
win++;
System.out.print("\t" + "you win!" + "\n");
break;
} else if (sum == 7) {
loss++;
start = false;
System.out.print("\t" + "you lose " + "\n");
break;
}
}
}
System.out.print("wins: " + win + "\n");
System.out.print("Losses:" + loss);
}
public void play() {
for (int x = 0; x < 3; x++) {
rolldice();
play(d1, d2);
System.out.print("\n");
}
}
public void rolldice() {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
System.out.print("You rolled " + d1 + " " + plus);
}
for (int i = 0; i < 1; i++) {
d2 = 1 + rand.nextInt(6);
System.out.print(" " + d2 + " ");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomSumGame Teet = new RandomSumGame();
RandomSumGame d1counter = new RandomSumGame();
RandomSumGame d2counter = new RandomSumGame();
Teet.play();
}
}
What part are you not able to finish? Seems like the game is running 3 times? Is it the total number of wins and loses? To fix that, you could just move "int win" and "int lose" outside the play method to make them global variables.
EDIT:
If you don't want to use global variables, you could make a method that calls itself (recursive method)
import java.util.Random;
public class RandomSumGame {
boolean start;
int d1;
int d2;
int sum = d1 + d2;
int valuepoint;
String plus = "+";
public void play(int d1, int d2, int win, int loss) {
sum = d1 + d2;
for (;;) {
if (sum == 2 || sum == 3 || sum == 12) {
start = false;
loss++;
System.out.println(" = " + sum + ";you lose");
break;
} else if (sum == 7 || sum == 11) {
start = true;
win++;
System.out.println(" = " + sum + ";you win ");
break;
}
valuepoint = sum;
if (valuepoint == 4 || valuepoint == 5 || valuepoint == 6 || valuepoint == 8 || valuepoint == 9
|| valuepoint == 10) {
System.out.print(" = " + valuepoint + " you establish a value point " + valuepoint + "\n");
break;
}
}
for (;;) {
if (sum == 7 || sum == 11) {
break;
} else {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
int f1 = d1;
System.out.print("\t" + "-you rolled again " + d1 + " " + plus);
for (int x = 0; x < 1; x++) {
d2 = 1 + rand.nextInt(6);
int f2 = d2;
int loda = f1 + f2;
System.out.print(" " + d2 + " = " + loda + "\n");
}
}
sum = d1 + d2;
if (sum == valuepoint) {
start = true;
win++;
System.out.print("\t" + "you win!" + "\n");
break;
} else if (sum == 7) {
loss++;
start = false;
System.out.print("\t" + "you lose " + "\n");
break;
}
}
}
System.out.print("wins: " + win + "\n");
System.out.print("Losses:" + loss);
if (win < 2 && loss < 2) {
System.out.print("\n");
//Recursive
play(win, loss);
}
}
public void play(int win, int loss) {
rolldice();
play(d1, d2, win, loss);
}
public void rolldice() {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
System.out.print("You rolled " + d1 + " " + plus);
}
for (int i = 0; i < 1; i++) {
d2 = 1 + rand.nextInt(6);
System.out.print(" " + d2 + " ");
}
}
public static void main(String[] args) {
RandomSumGame test = new RandomSumGame();
test.play(0,0);
}
}
I'm new to the programming world so I'd deeply appreciate if any of you could help me become better at this. My goal for this program is to simulate 3000 dice rolls and count the number of times doubles are rolled for each of the different possible pairs of doubles using a while loop. The results should be printed out in a dialog box.
Random random;
random = new Random();
diceRolls = 1;
snakeEyes = 1;
doubleTwos = 1;
doubleThrees = 1;
doubleFours = 1;
doubleFives = 1;
doubleSixes = 1;
while (diceRolls <= finalDiceRoll) {
int diceRolls = 1;
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1){
//snakeEyes = snakeEyes + 1;
snakeEyes++;
}
else if (die1 == 2 && die2 == 2 ) {
doubleTwos++;
}
else if (die1 == 3 && die2 == 3) {
doubleThrees++;
}
else if (die1 == 4 && die2 == 4) {
doubleFours++;
}
else if (die1 == 5 && die2 == 5) {
doubleFives++;
}
else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
JOptionPane.showMessageDialog (null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
}
The issue i'm having here is that the results i'm getting from the program don't seem "plausible". For example, out of 3000 dice rolls, I get 1 pair of each double. What am I doing wrong?
Few changes you have to make in your code,
1. Initialize all your variables by 0.
2. change while-loop condition to
while (diceRolls <= finalDiceRoll) // hoping that finalDiceRoll = 3000
3 remove int diceRolls = 1; from while-loop and add diceRolls++; at end of while-loop.
4. Put your JOptionPane outside while-loop. if not you have to close 3000 time your JOptionPane dailog.
After applying these changes to your code you will learn what have you done wrong and your code will run fine.
Move the showMessageDialog outside of the while loop and increment the diceRolls variable. Initialize all other integer variables with 0.
A better (cleaner and shorter) approach would be to use a two-dimensional array or a map.
Random random = new Random();
int snakeEyes = 0;
int doubleTwos = 0;
int doubleThrees = 0;
int doubleFours = 0;
int doubleFives = 0;
int doubleSixes = 0;
int diceRolls = 1;
while (diceRolls <= 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1) {
snakeEyes++;
} else if (die1 == 2 && die2 == 2) {
doubleTwos++;
} else if (die1 == 3 && die2 == 3) {
doubleThrees++;
} else if (die1 == 4 && die2 == 4) {
doubleFours++;
} else if (die1 == 5 && die2 == 5) {
doubleFives++;
} else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
diceRolls++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
The above-mentioned shorter version:
Random random = new Random();
int[] doubled = new int[6];
for (int diceRolls = 0; diceRolls < 3000; diceRolls++) {
int die1 = random.nextInt(6);
int die2 = random.nextInt(6);
if (die1 == die2)
doubled[die1]++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + doubled[0] + " times\nYou rolled double twos " + doubled[1] + " times\nYou"
+ " rolled double threes " + doubled[2] + " times\nYou rolled double fours " + doubled[3] + " times\nYou"
+ " rolled double fives " + doubled[4] + " times\nYou rolled double sixes " + doubled[5] + " times");
The counting logic should go as follows:
doubleTwos = 0;
doubleThrees = 0;
doubleFours = 0;
doubleFives = 0;
doubleSixes = 0;
finalDiceRoll = 3000;
int diceRolls = 0;
while (diceRolls < finalDiceRoll) {
++diceRolls;
With any message after the loop.
With an array you may save typing:
int[] doubleCounts = new int[6]; // By 0 based dice values
for (int i = 0; i < finalDiceRoll; ++i) {
int die1 = random.nextInt(6); // With dice values 0-5
int die2 = random.nextInt(6);
if (die1 == die2) {
++doubleCounts[die1];
}
}
int snakeEyes = doubleCounts[0];
int doubleTwos = doubleCounts[1];
...
Simplify. Eliminate duplications. Don't use multiple variables when you can use an array.
int[] doubles = new int[7]; // make the index the number rolled (ignore index 0)
int diceRolls = 0;
while (diceRolls++ < 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == die2)
doubles[die1]++;
}
String output = "";
for (int i = 1; i <= 6; i++)
output += "You rolled double " + i + "'s " + doubles[i] + " times\n";
JOptionPane.showMessageDialog (null, output);
That's all you need.
I want to take the array of random values I've generated and print the aforementioned array with parentheses outside the longest run of the same number.
For example, if the array was [0,1,1,1,2,4,7,4] I'd like to receive 0(111)2474 as an output.
This is my code thus far.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax {
runMax = counter;
runMin = i - counter + 1;
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter - 1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
}
}
try this code:
import java.util.Arrays;
import java.util.Random;
public class Snippet {
/**
* This method will generate my random numbers for my array.
*
* #param min
* minimum random value wanted
* #param max
* maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
// Part 1 - Generate a random array of length 40 with random 1-6
// inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
// Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
// Counts the longest run of the same number. A run continues only when
// consecutive numbers have the same value.
// RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 0;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax) {
runMax = counter;
startCounter = i - counter +2;
// runMin = i-counter+1;
variableNum = array1[i];
endCounter = i+1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax
+ " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter
+ " and ends at " + endCounter);
for (int i = 0; i < array1.length; i++) {
if (i==startCounter) {
System.out.print("(");
}
System.out.print(array1[i]);
if (i==endCounter) {
System.out.print(")");
}
}
System.out.println();
// Prints the array with parentheses outside the longest run, if there
// is more than one max run, use the last one.
}
}
Okay. I think I have this. The first answer was close, but if you run the program a few times, you discover issues. There is a logic error somewhere in your above code, but I have a work around. I think it is how you get the endCounter. It seems to count odd. But I got the program to work as far as I can tell. Try this out. I have run it several times and it seems consistent.
import java.util.Random;
import java.util.Arrays;
/**
* Write a description of class ArrayRunner1 here.
*
* #author Ibrahim Khan
* #version (a version number or a date)
*/
public class ArrayRunner1 {
/**
* This method will generate my random numbers for my array.
* #param min minimum random value wanted
* #param max maximum random value wanted
* #return randomNum a random number between 1 and 6 inclusive
*/
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static void main(String[] args) {
System.out.println("\f");
//Part 1 - Generate a random array of length 40 with random 1-6 inclusive
int[] array1 = new int[40];
for (int i = 0; i < array1.length; i++) {
array1[i] = randInt(1, 6);
}
System.out.println(Arrays.toString(array1));
//Counts and RETURN: reports how many times each number is present
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] == 1) {
counter1++;
}
if (array1[i] == 2) {
counter2++;
}
if (array1[i] == 3) {
counter3++;
}
if (array1[i] == 4) {
counter4++;
}
if (array1[i] == 5) {
counter5++;
}
if (array1[i] == 6) {
counter6++;
}
}
System.out.println("There are " + counter1 + " ones.");
System.out.println("There are " + counter2 + " twos.");
System.out.println("There are " + counter3 + " threes.");
System.out.println("There are " + counter4 + " fours.");
System.out.println("There are " + counter5 + " fives.");
System.out.println("There are " + counter6 + " sixes.");
//Counts the longest run of the same number. A run continues only when consecutive numbers have the same value.
//RETURN: The repeated number and the length of the run is then printed
int counter = 1;
int runMax = 1;
int runMin = 0;
int variableNum = 0;
int startCounter = 0;
int endCounter = 0;
for (int i = 0; i < array1.length - 1; i++) {
if (array1[i] == array1[i + 1]) {
counter++;
if (counter >= runMax ){
runMax = counter;
runMin = i - counter ;// was plus one I cahnged this.
variableNum = array1[i];
startCounter = i - counter + 2;
endCounter = i + counter -1;
}
} else {
counter = 1;
}
}
System.out.println("The longest run is " + runMax + " times and the number is " + variableNum + ". ");
System.out.println("The run starts at " + startCounter + " and ends at " + endCounter);
//Prints the array with parentheses outside the longest run, if there is more than one max run, use the last one.
String output = "";// added this
for(int x = 0; x < array1.length; x++)
{
if( x == startCounter)
{
output += "("+array1[x];
}
else if( x == startCounter + runMax )
{
else if( x == startCounter + runMax )
{
if(x == array1.length-1)
{
output += ")";
}
else
{
output += ")"+array1[x];
}
}
else
{
output += array1[x];
}
}
System.out.print("\n"+output);
}
}
Here's a shorter, more generic solution. This method takes any array of ints and prints parenthesis around the longest run of numbers. If there are two runs of the same lengths it prints it around the first one.
public String makeString(int[] ints) {
if (ints.length == 0) return ""; // Quit early if there's nothing to do.
// Initialize variables.
int lastNumber = ints[0];
// We keep track of the all time best run. Defaults to first int found.
int bestStart = 0;
int bestRun = 1;
// ... as well as the current run.
int currentStart = 0;
int currentRun = 1;
String s = ""+ints[0];
// Starting from the second int, we check if the current run is continuing.
for (int i = 1; i < ints.length; i++) {
int current = ints[i];
// If the current run continues, we update currentStart/currentRun, else we reset it.
if (current == lastNumber) {
currentRun++;
} else {
currentStart = i;
currentRun = 1;
}
// Now we check if the currentRun is better than the best.
// If so, we update bestStart/bestRun.
if (currentRun > bestRun) {
bestStart = currentStart;
bestRun = currentRun;
}
lastNumber = current;
s += current;
}
// Now that we've found it, we insert parenthesis aaaaaaand we're done!
return s.substring(0, bestStart)
+"("+s.substring(bestStart, bestStart+bestRun)+")"
+s.substring(bestStart+bestRun);
}
I am new to Java and was trying to learn by doing some excercises that I found online. So please excuse me if this is too naive.
This excercise was about writing a program for game of craps with the following rules:
In the game of craps, a pass line bet proceeds as follows: Two six-sided dice are
rolled; the first roll of the dice in a craps round is called the “come out roll.”
A come out roll of 7 or 11 automatically wins, and a come out roll of 2, 3, or 12
automatically loses. If 4, 5, 6, 8, 9, or 10 is rolled on the come out roll, that number
becomes “the point.” The player keeps rolling the dice until either 7 or the point is
rolled. If the point is rolled first, then the player wins the bet. If a 7 is rolled first,
then the player loses.
Write a program that simulates a game of craps using these rules without human
input. Instead of asking for a wager, the program should calculate whether the
player would win or lose. The program should simulate rolling the two dice and
calculate the sum. Add a loop so that the program plays 10,000 games. Add
c ounters that count how many times the player wins, and how many times the
player loses. At the end of the 10,000 games, compute the probability of winning
[i.e., Wins / (Wins + Losses)] and output this value. Over the long run, who
is going to win the most games, you or the house?
Here is the code that I have written :
// GAME OF CRAPS
public static void main (String[] args)
{
int dice1 = 0;
int dice2 = 0;
int scorenew = 0;
int point = 0;
int wins = 0;
int loss = 0;
for (int i = 0; i < 10000; i++)
{
System.out.println ("roll the dices");
int score = roll (dice1, dice2);
System.out.println ("\n score " + score);
if (score == 11 || score == 7)
{
System.out.println ("\n Score = " + score);
System.out.println ("you win");
wins = wins + 1;
}
if (score == 2 || score == 3 || score == 12)
{
System.out.println ("\n Score = " + score);
System.out.println ("you lose");
loss = loss + 1;
}
else if (score == 4 || score == 5 || score == 6 || score == 8 || score == 9 || score == 10)
{
point = point + score;
System.out.println ("\n Point = " + point);
do
{
scorenew = roll (dice1, dice2);
System.out.println ("\n Score new = " + scorenew);
if (scorenew == point)
{
System.out.println ("\n you win");
wins = wins + 1;
point = 0;
break;
}
if (scorenew == 7)
{
System.out.println ("\n you lose");
point = 0;
loss = loss + 1;
break;
}
} while (scorenew != point || scorenew != 7);
}
}
System.out.println ("\n number of wins = " + wins
+ " and number of loss = " + loss +
" and the probability for winning a game = " + (double) wins / (wins + loss));
}
public static int roll (int d1, int d2)
{
Random randomGenerator = new Random ();
int dice1 = randomGenerator.nextInt (6) + 1;
int dice2 = randomGenerator.nextInt (6) + 1;
System.out.println ("\n dice1 = " + dice1 + " dice2 = " + dice2);
int score = dice1 + dice2;
return score;
}
Everytime I run the code the do-while condition gets executed first, so please can anyone help me figure out where I am going wrong?
do {
} while(scorenew!=point || scorenew != 7);
This condition is always true, so you have an infinite loop. Also, why do you pass d1 and d2 into the roll() function? They are completely unused and unneeded.
Do while is doing exactly what it you should expect it to do. Executes the body first then evaluates the conditional to see if it should run again. You don't actually need a do while though, you want to run until one of the conditions breaks you out of the while loop.
else {
point = score;
System.out.println ("\n Point = " + point);
while (true) {
scorenew = roll (dice1, dice2);
System.out.println ("\n Score new = " + scorenew);
if (scorenew == point) {
System.out.println ("\n you win");
wins = wins + 1;
break;
}
if (scorenew == 7) {
System.out.println ("\n you lose");
loss = loss + 1;
break;
}
}
}
Like #Lee Daniel Crocker said you don't need to pass in dice1 and dice2 to the roll function.
public static int roll() {
Random randomGenerator = new Random();
int dice1 = randomGenerator.nextInt(6) + 1;
int dice2 = randomGenerator.nextInt(6) + 1;
System.out.println("\n dice1 = " + dice1 + " dice2 = " + dice2);
return dice1 + dice2;
}
Another thing that might help is not declaring all the variables at the top of your method. You don't need scorenew or point outside of the third condition, in fact you don't need scorenew at all since you have point:
public static void main(String[] args) throws java.lang.Exception {
int wins = 0;
int loss = 0;
for (int i = 0; i < 10000; i++) {
System.out.println("roll the dices");
int score = roll();
System.out.println("\n score " + score);
if (score == 7 || score == 11) {
System.out.println("\n Score = " + score);
System.out.println("you win");
wins = wins + 1;
} else if (score == 2 || score == 3 || score == 12) {
System.out.println("\n Score = " + score);
System.out.println("you lose");
loss = loss + 1;
} else {
int point = score;
System.out.println("\n Point = " + point);
while (true) {
score = roll();
System.out.println("\n Score new = " + score);
if (score == point) {
System.out.println("\n you win");
wins = wins + 1;
break;
}
if (score == 7) {
System.out.println("\n you lose");
loss = loss + 1;
break;
}
}
}
}
System.out.println("\n number of wins = " + wins
+ " and number of loss = " + loss +
" and the probability for winning a game = " + (double) wins / (wins + loss));
}
public static int roll() {
...
}
I'm working on a simple java code that outputs all factors of a user-inputted number. How do I count and then display the number of factors outputted?
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
}
}
In the code above, it's the number of integers outputted in 'w' For instance, if the number inputted is 8 and its factors are 1,2,4,8, how do I write a code that says '8 has 4 factors' ?
Thanks
You simply need a variable to count factors:
System.out.println("Enter an integer to be factored:");
int d = Stdin.readInt();
int nFactors = 0;
System.out.println("The Factors of " + d + " are:");
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
System.out.println(w);
++nFactors;
}
}
System.out.println(d + " has " + nFactors + " factors");
You need a counter variable. Here is the code:
int counter =0;
for(int w = 1; w <= d; w++ ){
if(d % w == 0){
counter++;
System.out.println(w);
}
System.out.println(d + " has " + counter + "factors ");
Try with this code:
import java.util.Scanner;
public class EmbalzadoFactorial {
public static Scanner sc;
public static void main(String[] args) {
int Number, i;
sc = new Scanner(System.in);
System.out.print("Please Enter any number to Find Factors: ");
Number = sc.nextInt();
System.out.println("The factors are: ");
for(i = 1; i <= Number; i++) {
if(Number%i == 0) {
System.out.format(" %d ", i);
System.out.print ("and");
System.out.format("%s %n ", i);
}
}
}
}