0

I'm trying to randomly pick a string from an array and spit it out to the user, but whenever I try to run it via AVD the app crashes. I'm very much a novice at this, and can't figure out what to do.

Here is my code:

public class MainActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final LinearLayout rr = new LinearLayout (this);

    // setting up the LinearLayout. I'll get to proper formatting one I get the code running.
    Button b1 = new Button (this);
    b1.setId(R.id.Button01);
    b1.setText("Generate");
    rr.addView(b1);
    final TextView tv;
    tv = new TextView(this);
    tv.setId(R.id.Text1);
    rr.addView(tv);
    setContentView(rr);

    final String [] columnA = { "artless", "bawdy", "beslubbering", "bootless", "churlish", "cockered", "clouted", "craven", "currish", "dankish", "dissembling", "droning", "errant", "fawning", "fobbing", "froward", "frothy", "gleeking", "goatish", "gorbellied", "impertinent", "infectious", "jarring", "loggerheaded", "lumpish", "mammering", "mangled", "mewling", "paunchy", "pribbling", "puking", "puny", "qualling", "rank", "reeky", "roguish", "ruttish", "saucy", "spleeny", "spongy", "surly", "tottering", "unmuzzled", "vain", "venomed", "villainous", "warped", "wayward", "weedy", "yeasty" };
    final String [] columnB = { "base-court", "bat-fowling", "beef-witted", "beetle-headed", "boil-brained", "clapper-clawed", "clay-brained", "common-kissing", "crook-patted", "dismal-dreaming", "dizzy-eyed", "doghearted", "dread-boiled", "earth-vexing", "elf-skinned", "fat-kidneyed", "fen-sucked", "flap-mouthed", "fly-bitten", "folly-fallen", "fool-born", "full-gorged", "guts-gripping", "hasty-witted", "half-faced", "hell-hated", "idle-headed", "ill-breeding", "ill-nurtured", "knotty-pated", "milk-livered", "motley-minded", "onion-eyed", "plume-plucked", "pottle-deep", "pox-marked", "reeling-riped", "rough-hewn", "rude-growing", "rump-fed", "shard-borne", "sheep-biting", "spur-galled", "swag-bellied", "tardy-gaited", "tickle-brained", "toad-spotted", "unchin-snouted", "weather-bitten"};
    final String [] columnC = { "apple-john", "baggage", "barnacle", "bladder", "boar-pig", "bugbear", "bum-bailey", "canker-blossom", "clack-dish", "clotpole", "coxcomb", "codpiece", "death-token", "dewberry", "flap-dragon", "flax-wench", "flirt-gill", "foot-licker", "fustilarian", "giglet", "gudgeon", "haggard", "harpy", "hedge-pig", "horn-beast", "hugger-mugger", "joithead", "lewdster", "lout", "maggot-pie", "malt-worm", "mammet", "measle", "minnow", "miscreant", "moldwarp", "mumble-news", "nut-hook", "pigeon-egg", "pignut", "puttock", "pumpion", "ratsbane", "scut", "skainsmate", "strumpet", "varlot", "vassal", "whey-face", "wagtail"};

    //Attempts to pick one string from each array, add "thou art a" and spaces, and display it to the device.
    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String outputA;
            Random r;
            r = new Random(columnA.length);
            Random s;
            s = new Random(columnB.length);
            Random t;
            t = new Random(columnC.length);
            outputA = "Thou art a" + " " + columnA[r.nextInt() % columnA.length] + " " + columnB[s.nextInt() % columnB.length] + " " + columnC[t.nextInt() % columnC.length];
            tv.setText(outputA);
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
6
  • 1
    I strongly suggest you read the documentation for the Random constructor and the nextInt method. They don't do what you think they do. Commented Jul 13, 2013 at 15:43
  • As @JonSkeet says check the documentation. The parameter passed to the Random constructor is the seed for the random number generator. You can leave this parameter out as Random will use a "good enough" seed for what you are trying to do. You pass the range for the random number on the nextInt call. Commented Jul 13, 2013 at 15:48
  • You should also post the logcat stack trace when asking about a crash. It identifies exactly what the problem is. Commented Jul 13, 2013 at 15:48
  • @JonSkeet I'll be sure to do so. In the meantime, though, Ken Wolf's solution is working great. Commented Jul 13, 2013 at 16:22
  • @user2540201: But do you understand why it wasn't working before? If not, you haven't really learned anything from the question. Commented Jul 13, 2013 at 16:23

1 Answer 1

2

I imagine you were getting an ArrayIndexOutOfBoundsException

To solve, remove all the Randoms and change your onClickListener to:

b1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String outputA = "Thou art a" + " " + columnA[(int) (Math.random() * columnA.length)] + " " + columnB[(int) (Math.random() * columnB.length)] + " " + columnC[(int) (Math.random() * columnC.length)];
        tv.setText(outputA);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

While using Math.random() works, it's not as clean (IMO) as using Random - but doing so properly.
@JonSkeet Fair dos. Sometimes all folk want is a timely solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.