じゃんけんゲームを以下のように作ってみましたが、どのボタンを押してもResultActivityでグーの画像が表示されてしまいます。
LogでcpuHandとR.id.chokiの値が一致していることを確認しましたがその場合もcase R.id.chokiの部分が実行されません。
しかし、グーを押したときにはcase R.id.guの部分が実行されることを確認しました。
MainActivity
1package com.example.janken; 2 3import android.content.Intent; 4import android.support.v7.app.AppCompatActivity; 5import android.os.Bundle; 6import android.util.Log; 7import android.view.View; 8import android.widget.ImageButton; 9 10public class MainActivity extends AppCompatActivity { 11 12 private ImageButton buttonGu; 13 private ImageButton buttonChoki; 14 private ImageButton buttonPa; 15 16 @Override 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 buttonGu = findViewById(R.id.gu); 21 buttonChoki = findViewById(R.id.choki); 22 buttonPa = findViewById(R.id.pa); 23 } 24 25 public void janken(View v){ 26 Intent intent = new Intent(this, ResultActivity.class); 27 int id = v.getId(); 28 intent.putExtra("HAND",id); 29 startActivity(intent); 30 } 31}
ResultActivity
1package com.example.janken; 2 3import android.content.Intent; 4import android.support.v7.app.AppCompatActivity; 5import android.os.Bundle; 6import android.util.Log; 7import android.widget.ImageView; 8import android.widget.TextView; 9 10import java.util.Random; 11 12public class ResultActivity extends AppCompatActivity { 13 14 private ImageView myHandView; 15 private ImageView cpHandView; 16 private TextView resultView; 17 18 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_result); 23 myHandView = findViewById(R.id.cpHandView); 24 cpHandView = findViewById(R.id.cpHandView); 25 resultView = findViewById(R.id.resultText); 26 27 Intent intent = getIntent(); 28 int handId = intent.getIntExtra("HAND",0); 29 30 int myHand =0; 31 32 switch (handId){ 33 case R.id.gu: 34 myHand = 0; 35 myHandView.setImageResource(R.drawable.gu); 36 break; 37 case R.id.choki: 38 myHand = 1; 39 myHandView.setImageResource(R.drawable.choki); 40 break; 41 case R.id.pa: 42 myHand = 2; 43 myHandView.setImageResource(R.drawable.pa); 44 break; 45 } 46 47 Random random = new Random(); 48 int cpuHand = random.nextInt(3); 49 50 switch (cpuHand){ 51 case 0: 52 cpHandView.setImageResource(R.drawable.com_gu); 53 break; 54 case 1: 55 cpHandView.setImageResource(R.drawable.com_choki); 56 break; 57 case 2: 58 cpHandView.setImageResource(R.drawable.com_pa); 59 break; 60 } 61 62 switch ((myHand-cpuHand+3)%3){ 63 case 0: 64 resultView.setText("あいこ"); 65 break; 66 case 1: 67 resultView.setText("負け"); 68 break; 69 case 2: 70 resultView.setText("勝ち"); 71 } 72 73 } 74}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。