Question:

How to copy a String in Java

by  |  earlier

0 LIKES UnLike

I have a class that randomly generates 5 numbers between the numbers 1-5. The numbers are placed in an array in the client class. I would like to print out an asterisk (*) that represents the number of times each number was randomly generated. So for 5 numbers if the number 1 was generated once and the number 2 generated 4 times, it would read:

1*

2****

3

4

5

I have this class:

import java.util.Random;

public class Rand

{

public final int total = 5;

private Random rand;

public Rand()

{

rand = new Random();

}

public int generate()

{

return rand.nextInt(total) 1;

}

}

and this client:

public class Starcount

{

public static void main(String [] args)

{

Rand random = new Rand();

int [] counter = new int [5];

StringBuffer star = new StringBuffer();

for (int i=1; i <= counter.length; i )

{

int myRoll = random.generate();

counter[myRoll-1] ;

}

for (int i=0; i < counter.length; i )

{

System.out.println((i 1) "\t" counter[i]);

}

}

}

Any ideas?

 Tags:

   Report

2 ANSWERS


  1. Java question and answer-http://javaanswers1.blogspot.com/


  2. I suggest creating an array of size 6. From your description, it sounds like you are not going to use index 0. As you generate numbers, you can do this bit of code: (I assume that there is supposed to a plus sign in this line: rand.nextInt(total) 1 so that it reads: rand.nextInt(total) + 1)

    Rand gen = new Rand();

    int[] holder = new int[6];

    for(int i = 0; i &lt; 5; i++)

         holder[gen.generate()]++;

    for(int index = 1; index &lt; holder.length; index++)

    {

        // index is 1 to skip 0

        String s = new String();

        for(int i  = 0; i &lt; n; i++)

            s += &quot;*&quot;;

        System.out.println(n + &quot;\t&quot; + s);

    }

    You can put an if statement in the Rand class to prevent an ArrayIndexOutOfBounds Exception. If you have more questions, email me at steventan_12@yahoo.com

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.