# Thread: Array Help

1. Member
Join Date
Nov 2011
Location
San Jose, CA
Posts
4
Rep Power
0

## Array Help

Hello, I am trying to create a method that will out put 3 random variables consisting of either 7, Cherry, Space, or Bar (it's part of a slot machine). I am new to arrays and I am not sure out to put an out put of an operation and put it inside an array. The problem I am having is at the bottom of my code.
Java Code:
```      String[] total = new String[3];
String var = "0";
Random rand = new Random();
for (int j=0; j < 3; j++)
{
int pickedNumber = rand.nextInt(8) + 1;
if (pickedNumber == 1)
{
var = "7";
}
else if (pickedNumber == 2)
{
var = "Cherry";
}
else if (pickedNumber == 3 || pickedNumber == 4)
{
var = "Space";
}
else if (pickedNumber == 5 || pickedNumber == 6 || pickedNumber == 7
|| pickedNumber == 8)
{
var = "Bar";
}
System.out.print(var + " ");
total[3] += var;
System.out.println(total[0]);
}
}
}```
It returns with a run time error, it appears that the var is being put into the array.

Any help would be greatly appreciated!
-Dexter

2. Member
Join Date
Oct 2011
Posts
14
Rep Power
0

## Re: Array Help

The problem was, you created an Array with a size of 3, but you used a wrong index :).
If you create an Array with a size of 3, you have the index: 0, 1, 2, which means, an array begins with 0
and not with 1 :).
The second thing is, its not a good idea to put it all in index 2 if you made an array with a size of 3, instead you should
use the whole array :).

Here the fixed code:

Java Code:
```import java.util.Random;

public class Test
{
public static void main(String[] args)
{
String[] total = new String[3]; // Creates and String Array with a size of 3
String var = "0";
Random rand = new Random();
for (int j=0; j < 3; j++)
{
int pickedNumber = rand.nextInt(8) + 1;
if (pickedNumber == 1)
{
var = "7";
}
else if (pickedNumber == 2)
{
var = "Cherry";
}
else if (pickedNumber == 3 || pickedNumber == 4)
{
var = "Space";
}
else if (pickedNumber == 5 || pickedNumber == 6 || pickedNumber == 7
|| pickedNumber == 8)
{
var = "Bar";
}

total[j] = var;	// Put the String to the correct place (first loop: j = 0, second loop: j = 1, third loop: j = 2)
}

System.out.println(total[0]); // Output the String at index 0 of the Array
System.out.println(total[1]);	// Output the String at index 1 of the Array
System.out.println(total[2]); // Output the String at index 2 of the Array
}
}```

3. Member
Join Date
Nov 2011
Location
San Jose, CA
Posts
4
Rep Power
0

## Re: Array Help

Awesome! thank you :)

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•