Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Crystal Ball app using with String Resource

Hello, I am redoing the Crystal Ball app using String Resources how do i incorporate it to the activity?

public class crystalball{

public String getAnAnswer(){

String[] facts = { 
          "item 1 ",
          "item 2" };

    String fact ="";
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber]; 
return fact;

} }

String array name is factsarray

1 Answer

You don't need to store two values in an array for this.

List the string constants as shown below under /res/values/ in the strings.xml file:

<string name="false">Whatever you want to be false</string>
<string name="true">Whatever you want to be true</string>

Implement the following code as shown below in your java file:

public class CrystalBall
{

    public String getAnAnswer( )
    {

        String[ ] facts = new String[ 2 ];

        facts[ 0 ] = new String( getString( R.string.false ).toString( ) );
        facts[ 1 ] = new String( getString( R.string.true ).toString( ) );

        boolean isFact = false;
        int randomNumber = ( int )( Math.random( ) *101 );

        if( ( randomNumber <= 50 ) && ( randomNumber >= 0 ) )
        {

            isFact = true;

        }

        if( isFact )
        {

            return facts[ 1 ];

        }
        else
        {

            return facts[ 0 ];

        }

    }

}