TextView,EditText,Buttonを使った問題。
Q1
0〜99の値を一つランダムに生成し、その数字を当てるゲームを作成せよ。
入力した値よりも正解が小さい場合は
「もっと下だよ」
入力した値よりも大きい場合は
「もっと上だよ」
正解の場合は
「正解!」
と出力するものとする。
NEW GAMEボタンも配置し、繰り返しゲームをできるようにすること。
詳しくは実行例を参照のこと
[実行例]
スタート画面

数字を入力し、CHECKボタンを押すと下にヒントが表示される。

正解すると「正解!」と表示

NEW GAMEボタンを押すと新しいゲーム開始

●activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="いくつかな?(0~99)"
android:layout_marginTop="33dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="@+id/etNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/textView"
android:layout_below="@+id/textView"
android:layout_marginTop="12dp"
android:ems="10"
android:inputType="number"
android:layout_alignEnd="@+id/textView" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="@+id/etNum"
android:layout_marginTop="17dp"
android:onClick="btCheck"
android:text="Check!" />
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:textAlignment="center"
android:textSize="18sp" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="btNewGame"
android:text="New Game" />
</RelativeLayout>
●MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private Random r=new Random();
private EditText etNum;
private TextView tvResult;
private int answer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNum=(EditText)findViewById(R.id.etNum);
tvResult=(TextView)findViewById(R.id.tvResult);
init();
}
private void init() {
answer=r.nextInt(100);
etNum.setText("");
tvResult.setText("");
}
public void btCheck(View v){
int input=Integer.parseInt(etNum.getText().toString());
String msg;
if(input > answer){
msg="もっと下だよ";
}else if(input < answer){
msg="もっと上だよ";
}else{
msg="正解!";
}
tvResult.setText(msg);
}
public void btNewGame(View v){
init();
}
}

コメント