-1

I've only just begun to learn Java and i'm trying to switch multiple booleans based on input. I want to do this in a method that is scaleable and a little more elegant than writing out an if statement for every possibillity. the idea is this:

int vikingcount = (input.nextInt());
while (vikingcount>0) {
    V(vikingcount)=true;
    vikingcount--;
}

Now I'm fully aware that the above code does not work. There are multiple booleans named V1, V2, V3 etc. and i would like the method to set the amount given by the input to true (so if the input is 3, V1 V2 and V3 would be set to true) How would I accomplish this? your help is much appreciated.

Shashwat
  • 2,342
  • 1
  • 17
  • 33

2 Answers2

1

I think you want an array of boolean(s), get the count from the user, initialize the array, and then use Arrays.fill(boolean[], boolean) like

int vikingcount = input.nextInt();
boolean[] vikings = new boolean[vikingcount];
Arrays.fill(vikings, true);

If you have some number to be true, and some false you can use Arrays.fill(boolean[], int, int, boolean) to fill n true and y false like,

System.out.println("How many total?");
int vikingcount = input.nextInt();
System.out.println("How many true?");
int n = input.nextInt();
boolean[] vikings = new boolean[vikingcount];
Arrays.fill(vikings, 0, n, true);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

I think the best way to do this, is to create an array of booleans.

boolean[] V = new boolean[numberOfBools];
int vikingcount = (input.nextInt());

for(int i = (vikingcount - 1); i >= 0; i--)   // This loops through the whole array
{                                   
    V[i] = true;
}

Note that an array Counting starts with 0. So if you have 5 Elements in that array, they will be named V[0], V[1], V[2], V[3] and V[4].

O.O.Balance
  • 2,930
  • 5
  • 23
  • 35
IX33U
  • 85
  • 4