-2

char[] colors={'R','G','B','Y','W'};

Scanner sc=new Scanner(System.in);
Stack stack=new Stack();

void push(){
        for(int i=0; i<15; ++i){

            stack.push();
        }

I've got an array of colors and i want to push random colors into a stack unto 15 elements. How can i push and display all the elements in the stack.

John doe
  • 33
  • 1
  • 2
  • 9
  • 2
    http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range – orkan Feb 03 '16 at 17:16

2 Answers2

1

Try to use something like this:

char[] colors = {'R', 'G', 'B', 'Y', 'W'};

void push() {
    for (int i = 0; i < 15; ++i) {
        // define a random int to pick char from array index from 0 to colors.length -1
        int idx = new Random().nextInt(colors.length);
        // push the element into stack
        stack.push(colors[idx]);
    }
}
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
  • Thank you abdelhak. it worked. i was passing just idx into push. – John doe Feb 03 '16 at 17:58
  • I'm trying to pop elements of a particular color by taking the color as input.. void pop(String s){ stack.pop(s);} – John doe Feb 03 '16 at 18:33
  • @Johndoe try to use this link [http://stackoverflow.com/questions/19647713/removing-a-specific-element-in-a-stack](http://stackoverflow.com/questions/19647713/removing-a-specific-element-in-a-stack) – Abdelhak Feb 03 '16 at 20:36
0

When defining the Random object, it is good to do this once and then reuse the object. Random uses the current time in milliseconds as the seed for constructing the random numbers. In a very fast loop like this, the milliseconds probably will not change much (or at all), so you will be "randomly" creating several of the same number in a row.

Here's the example code:

Stack stack=new Stack();
char[] colors={'R','G','B','Y','W'};
void push(){
    Random random = new Random();
    for(int i=0; i<15; ++i){
        int randomIndex = random.nextInt(colors.length);
        stack.push(colors[randomIndex]);
    }
}
Brian Risk
  • 1,244
  • 13
  • 23