Question: I need help figuring out the rest of this code, the question is as follows: Write a program that generates a sequence of 20 random
I need help figuring out the rest of this code, the question is as follows:
Write a program that generates a sequence of 20 random die tosses in an array and that prints the values, marking only the longest run, like this:
1 2 5 5 3 1 2 4 3 (2 2 2 2 2) 3 6 5 5 6 3 1
If there is more than one run of maximum length, mark the first one.
This is what I have so far, but I occasionally get an "out of bounds error" and when marking the run it only marks the first 2 values everytime. Any help would be greatly appreciated!
import java.util.*;
public class Project_1 {
public static void main(String[] args) { int [] dice = new int[21]; String str = ""; Random rand = new Random(); for (int i=0; i<20; i++) { dice [i] = rand.nextInt(6)+1; } for (int i=0; i<20; i++) { str = str + dice[i]; } System.out.println(str); int count = 0; int maxcount = 0; int endPosition = 0; boolean inMax = false; for (int i=0; i<20; i++) { if (dice[i] == dice [i+1]) { count ++; if (count >= maxcount) { maxcount = count +1; inMax = true; } } if (dice[i] != dice[i+1]) { if (inMax) { endPosition = 1; inMax = false; } count = 0; } } int startPosition = endPosition - maxcount + 1; System.out.println(str.substring(0,startPosition)+"("+str.substring(startPosition,endPosition + 1)+")"+str.substring(endPosition + 1,20)); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
