Winter One
Winter One

Reputation: 27

How do you change each part of an array?

So here is the code I have right now.

public static void main(String[] args) {
    Scanner keyboard = new Scanner (System.in);
    int set[] = new int[5];
    set[0] = (int)(Math.random()*6)+1;
    set[1] = (int)(Math.random()*6)+1;
    set[2] = (int)(Math.random()*6)+1;
    set[3] = (int)(Math.random()*6)+1;
    set[4] = (int)(Math.random()*6)+1;

    System.out.println("Your current dice: " + set[0] + " " +  set[1] + " " + set[2] + " " + set[3] + " " +set[4] );
    System.out.println("Select a die to re-roll (-1 to keep remaining dice):");
    int ask = keyboard.nextInt();

After this if the user types in let's say 1 then set[1] should change to the number zero and so it becomes x0xxx and if the user also wants the 3rd number to change then it should be x0x0x.

The x's are just the generated random numbers by the way.

How do I keep doing this? It has to be a total of utmost 5 times.

Upvotes: 0

Views: 115

Answers (2)

Edwin Buck
Edwin Buck

Reputation: 70979

The way you do one thing many times is in a loop. The key is in learning which kind of loop to use.

For things that get applied to every element, use a for-each loop. For things that need done until some condition use a while loop. For things that need done until some condition becomes false, use a do-until loop.

The thing you do is the same, that goes into the block of the loop. The thing you are "working on" changes, that is a variable which the loop will set each time it "goes through" the loop's block.

In your case

for (Die die : dice) {
  die.roll();
}

where class Die looks like

public class Die {

  private int value;

  public Die() {
    roll();
  }

  public void roll() {
    value = (int)(Math.random()*6)+1;
  }

  public int getValue() {
    return value;
  }
}

Then, since you need "order" (first, second, third, etc...) use a data structure that can contain Objects (like your Die)

List<Die> dice = new ArrayList<>();

Arrays are nice, and you do need to know how to use them; however, there are far better ways of solving most problems by not using them.

When you really can't get around using them, use a for loop to walk each array index.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

Here are the basic steps you should follow to accomplish what you want/need.

  1. Read user input (using Scanner or something else).
  2. Validate if the user input is a valid index for the array (this is, the input is a number with a value between 0 and 5). You can store this in a variable int x.
  3. Change the value of the element of the array inside the index user entered to 0 (or the value you want/need). This would traduce into something like set[x] = ... (change the ... by the proper value).

Upvotes: 2

Related Questions