android studio猜数字游戏代码
时间: 2023-06-30 10:13:05 浏览: 80
好的,以下是一个简单的猜数字游戏的 Android Studio 代码示例:
首先,在 `activity_main.xml` 文件中添加以下代码:
```xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Guess a number between 1 and 100"
android:textSize="18sp"
android:textStyle="bold"
android:layout_marginTop="32dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:textAlignment="center"/>
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:inputType="number"/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Guess"
android:textSize="18sp"
android:layout_marginTop="32dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_gravity="center_horizontal"/>
```
然后,在 `MainActivity.java` 文件中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private int randomNumber;
private TextView textView;
private EditText editText;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
editText = findViewById(R.id.editText);
button = findViewById(R.id.button);
// Generate a random number between 1 and 100
randomNumber = new Random().nextInt(100) + 1;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the user's guess
int guess = Integer.parseInt(editText.getText().toString());
if (guess == randomNumber) {
textView.setText("Congratulations! You guessed the number!");
} else if (guess < randomNumber) {
textView.setText("Too low! Try again.");
} else {
textView.setText("Too high! Try again.");
}
}
});
}
}
```
这些代码将生成一个随机数,然后让用户猜测该数字,最后告诉用户他们的猜测是太高还是太低,或者如果他们猜对了,就显示“恭喜你猜对了!”。您可以根据需要进行修改和调整。