I'm extremely new to Java, but decided to create a simple game. When you press a button, the program "flips a coin" and displays either "True" or "False."
The idea is that based on a random generated number, it will either display "True" or "False."
This is my 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 I attempt to run I get an 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
at com.me.koteg.dmaker.MainActivity$1.onClick(MainActivity.java:34)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21153)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I have a feeling that I might have wrote the code completely wrong, but any suggestions/help from you guys would be great!
Aucun commentaire:
Enregistrer un commentaire