mememe123
mememe123

Reputation: 13

Java code how to append a color to a list a certain number of times

How would I code a method (named extendSequence) that appends a color to a list a certain number of times. It accepts three parameters in the following order: A list of colors of type ArrayList A color to add of type Color A run-length, or the number of times to append the color, of type int

For example: suppose a list contains Color.Red and Color.Blue. Then the method extendSequence(list, Color.Blue, 2) changes the list so that it has the elements [Color.Red, Color.Green, Color.Blue, Color.Blue].

Upvotes: 1

Views: 988

Answers (2)

dancingbush
dancingbush

Reputation: 2281

Try:

List<Color> colours = new ArrayList<Color>();
         colours = extendedSequence(colours, Color.blue, 10);
         System.out.println(colours);


    }

    public List<Color> extendedSequence(List<Color> colours, Color addColor, int numberOfTimes ){

while (numberOfTimes != 0) {
            colours.add(addColor);
            numberOfTimes --;
        }

        return colours;

    }

Upvotes: 0

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79620

You can do it as follows:

import java.util.ArrayList;
import java.util.List;

enum Color{
    Red,
    Green,
    Blue
}

public class Main {
    public static void main(String[] args) {
        List<Color> list=new ArrayList<Color>();
        list.add(Color.Red);
        list.add(Color.Green);
        System.out.println(list);
        extendSequence(list, Color.Blue, 2);
        System.out.println(list);
    }
    public static void extendSequence(List<Color> list, Color color, int times){
        if(list!=null) {
            for(int i=1;i<=times;i++)
                list.add(color);
        }
    }
}

Output:

[Red, Green]
[Red, Green, Blue, Blue]

Upvotes: 1

Related Questions