user615525
user615525

Reputation: 353

Random Int Function Generating Application Force Close

I am having difficulty finding out why the following line of code is generating a 'Force Close' in my Android Application:

    fact = myArray[randfact.nextInt(myArray.length)];

I have an arracy of interesting facts - just a Siring Array. It's defined in a file called array.xml and it has the name myArray.

The actual code snippet to generate the random fact is:

Random randfact = new Random();
fact = myArray[randfact.nextInt(myArray.length)];

where fact is of type string and I define myArray as an Array of Strings PRIOR to the above two lines of code:

String fact;    
String[] myArray;

I believe the culprit is:

fact = myArray[randfact.nextInt(myArray.length)];

because when I comment out the line as such:

//fact = myArray[randfact.nextInt(myArray.length)];

my Application no longer generates a 'Force Close'. Does anyone notice anything? I can't seem to find it!!!

Upvotes: 1

Views: 385

Answers (4)

Kevin
Kevin

Reputation: 1200

How are you initialising your array. You need something like:

myArray= getResources().getStringArray(R.array.myArray);

Upvotes: 1

Nick Campion
Nick Campion

Reputation: 10479

As always, you'll want to divide your command out into multiple lines.

Log.d("TEST","Array length: "+myArray.length)
int nexti = randfact.nextInt(myArray.length)
Log.d("TEST","Random fact index: "+nexti)
fact = myArray[nexti];

While the answer is probably clear that passing 0 to random.nextInt will throw an exception, you should understand how to determine the answer to these questions yourself.

Upvotes: 0

johusman
johusman

Reputation: 3472

If you pass 0 to Random.nextInt(n) it will throw an IllegalArgumentException - which in your case happens when myArray is a zero length array.

Upvotes: 1

Ollie C
Ollie C

Reputation: 28519

Look in the Android log (logcat) and it will tell you what the error is. With the device/emulator connected, run ddms.bat and it will show the log, or show Logcat in the IDE.

Upvotes: 0

Related Questions