java - How to Display a Random Word out of a Set? -
i'm extremely new java, decided create simple game. when press button, program "flips coin" , displays either "true" or "false".
the idea based on random generated number, either display "true" or "false".
this current code:
package com.me.koteg.dmaker; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.textview; import java.util.random; public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } public void generate(view view) { final textview textone = (textview) findviewbyid(r.id.txtdisplay); button pushme = (button) findviewbyid(r.id.button); final string[] mycoin= {"heads", "tails"}; random rand = new random(); int number = rand.nextint(3); pushme.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { textone.settext(mycoin[3]); } }); but when ever attempt run error:
01-05 18:26:58.644 22736-22736/com.me.koteg.dmaker e/androidruntime: fatal exception: main process: com.me.koteg.dmaker, pid: 22736 java.lang.arrayindexoutofboundsexception: length=2; index=3 @ com.me.koteg.dmaker.mainactivity$1.onclick(mainactivity.java:34) @ android.view.view.performclick(view.java:5204) @ android.view.view$performclick.run(view.java:21153) @ android.os.handler.handlecallback(handler.java:739) @ android.os.handler.dispatchmessage(handler.java:95) @ android.os.looper.loop(looper.java:148) @ android.app.activitythread.main(activitythread.java:5417) @ java.lang.reflect.method.invoke(native method) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:726) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:616) i have feeling might have wrote code wrong, suggestions/help guys great!
update: help, guys. didn't think i'd quickly, after looking android forums , not getting thorough response. of pointed out, number had set in random generator.
do want new random number on each press? code close. when random number using nextint gets number between 0 inclusive , pass in exclusive.
since array has 2 elements want either 0 or 1 , need pass in 2. need index array using random number instead of hard coding number.
the original code failing because specified invalid index array. stated in exception has length 2 , specified index 3 invalid since arrays indexed starting @ 0.
pushme.setonclicklistener(new view.onclicklistener() { public void onclick(view v) { int number = rand.nextint(2); textone.settext(mycoin[number]); } });
Comments
Post a Comment