i have to write a program for generating 20 tosses of a die and then grouping them by placing parentheses around them like this:
1 3 ( 2 2 ) 3 5 2 ( 6 6 ) 5 ( 1 1 1 ) ( 4 4 ) 2 3 ( 5 5 ) 1
i have to have a seperate class to create the array, but in that class i have to create a method to mark the runs in parentheses...i have figured out how to do that, but it must be returned as a string and i cannot figure out how to do that...any help is appreciated...
here is what i have for my constructor class:
/**
This class marks "runs", i.e., adjacent repeated values, by
including them in parenthesis.
For example:
1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1
*/
public class Sequence
{
private int[] values;
public Sequence(int capacity)
{
values = new int[capacity];
}
/**
Returns the string of values, with runs enclosed in parentheses.
@return the string of values with the runs marked, for example
"1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1"
*/
public String markRuns()
{
String answer = "";
for (int i = 1; i < values.length; i++)
{
if (values[i] == values[i-1] && values[i] == values[i+1])
answer = values[i] + "";
if (values[i] != values[i-1] && values[i] == values[i+1])
answer = "(" + values[i] + "";
if (values[i] != values[i-1] && values[i] == values[i+1])
answer = "" + values[i];
if (values[i] == values[i-1] && values[i] != values[i+1])
answer = "" + values[i] + ")";
}
}
and here is the main class and what it is calling for:
import java.util.Random;
/**
This class generates random die tosses and prints them out,
marking "runs", i.e., adjacent repeated values, by
including them in parenthesis.
For example:
1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1
*/
public class DieSequencePrinter
{
public static void main(String[] args)
{
final int TOSSES = 20;
Random die = new Random();
Sequence seq = new Sequence(TOSSES);
/* fill the array with random die tosses */
for (int i = 1; i <= TOSSES; i++)
{
seq.add(die.nextInt(6) + 1);
}
System.out.println(seq.markRuns());
}
}