0

I'm working on a small game that essentially has piles of coins, and you must take some coins from a pile then the program prints out the resulting piles in the format:

Pile 1: ****
Pile 2: *****
Pile 3: **

I have an array list that store all these values like so:

List<Integer> coins = new ArrayList<>();
[4,5,2]

But I can't figure out how to get it to properly print the *'s.

How can I write this code to print out a * for each value in an element. IE 4 *'s if the element value is 4?

Here is my current method:

static void printGameState(){
    for(int i = 0; i <= coins.size()-1; i++){
        int k = i+1;
        System.out.print("Pile " + k + ": ");
        for(int j = 0; j <= coins.indexOf(i); j++){
            System.out.print("*");
        }
    }
}

3 Answers 3

1

Instead of using this condition:

j <= coins.indexOf(i);

Use this condition:

j < coins.get(i);

Try it:

for(int i = 0; i <= coins.size()-1; i++) {
    int k = i+1;

    System.out.print("Pile " + k + ": ");
    for(int j = 0; j < coins.get(i); j++) {
        System.out.print("*");
    }

    System.out.println();
}

You'll get:

Pile 1: ****
Pile 2: *****
Pile 3: **
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this was very helpful. If I wanted to subtract the value of one of the arraylist elements, how would I go about doing this? coins.set(index, coins.get(index) - numCoins); would this be correct?
1

You should be using < instead of <=. Also, you should be able to use get(i) to take the value at index i.

static void printGameState(){
    for(int i = 0; i < coins.size(); i++){
        int k = i+1;
        System.out.print("Pile " + k + ": ");
        for(int j = 0; j < coins.get(i); j++){
            System.out.print("*");
        }
    }
}

You could also make it a bit cleaner by forming another method to print * such as:

public void ast(int n){
    for(int i=0; i<n; i++){
        System.out.print("*");
    }
}

Then the contents of printGameState loop would be

int k = i+1;
System.out.print("Pile " + k + ": ");
ast(coins.get(i));

Comments

1

You have to look at the values of the different stacks by accessing the array coins[i] instead of using the number of stacks as stack height:

static void printGameState(){
    for(int i = 0; i < coins.size(); i++) {
        // Build the coin stack
        String coinStack = "";
        for(int j = 0; j < coins.get(i); j++) {
            coinStack += "*";
        }

        // And output it
        System.out.println("Pile " + (i + 1) + ": " + coinStack);            
    }
}

1 Comment

coins is not type int[] so coins[i] wouldn't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.