derek00101110 derek00101110 - 28 days ago 17
Java Question

Write a program that generates a random sequence of 20 die tosses

I have very little experience in programming, and I am taking my first programming course in college right now. We have a problem in class to write a program that generates a sequence of random numbers from 1 to 6 and place parentheses around series of consecutive numbers. For example, if the sequence was 12553124322223655631, the program would print 12(55)31243(2222)36(55)631.

Here is the code I have so far:

package inRun;
import java.util.Random;

public class Prob612 {
public static void main(String args []){
Random rand = new Random();
boolean inRun = false;
int i = 0;

int [] values;
values = new int[20];


while (i < values.length){
int j = rand.nextInt(7);
if (j > 0 && j <= 6){
values[i] = j;
i++;
}
}

for (i = 0; i < values.length; i++){
if (inRun){
if (values[i] != values[i + 1]){
System.out.print(")");
inRun = false;
}
}
if (inRun = false){
if (values[i] == values[i - 1]){
System.out.print("(");
inRun = true;
}
}
System.out.print(values[i]);
}

if (inRun){System.out.print(")");}
}

}


When I run this program, it prints the sequence, but without the parentheses. I'm thinking that I would need to use an enhanced
for
loop, but I have no idea how I would go about doing that with a program like this. Any insight would be appreciated. Thank you.

Answer

You have almost solved it. Two things to be aware of:

  • You are assigning the boolean to false inside the if statement. (inRun = false) should be ( inRun == false ).
  • You are overrunning the array with values[i + 1] when on the last item.

This should do it.

  boolean inside = false;

  for (int i = 0; i < values.length; i++) {
      if (inside) {
        if (values[i] != values[i - 1]) {
            System.out.print(')');
            inside = false;
        }

      } else {
        if (i < values.length - 1) {
            if (values[i + 1] == values[i]) {
                System.out.print('(');
                inside = true;
            }
        }
      }
      System.out.print(values[i]);
  }