标签:trim 游戏 long tool cal 影响 creat int next
功能介绍:该程序能够提示猜大了猜小了,并且对空白输入处理,还对猜测次数限制,提供重置功能。
1、先看界面,一个输入框EditText,两个Button
2、界面设计 activity_main2.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".Main2Activity"> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="number" /> <Button android:id="@+id/button16" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="提交" /> <Button android:id="@+id/button17" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="重新开始" /> </LinearLayout>
3、逻辑事件控制 Main2Activity.java
package com.example.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.util.Random; public class Main2Activity extends AppCompatActivity { private Button sure=null; private Button reset=null; int num = 5; //机会次数 private EditText input_object=null; Random random = new Random(10); int rand = random.nextInt(10); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); sure = (Button) findViewById(R.id.button16); reset = (Button) findViewById(R.id.button17); input_object = (EditText) findViewById(R.id.editText2); sure.setOnClickListener(new View.OnClickListener() {//监听确认按钮 @Override public void onClick(View v) { String empt=input_object.getText().toString().trim();//提前检测输入是否为空 if(num>0) {//机会用完就不能猜了 if (empt.isEmpty()) {//判断输入是否为空 Toast.makeText(Main2Activity.this, "你大爷的!别乱点。。。", Toast.LENGTH_LONG).show(); } else { num--;//机会减少 int inputnum = (int) Integer.parseInt(input_object.getText().toString());//如果输入为空会产生致命影响 if (inputnum == rand) {//猜对 Toast.makeText(Main2Activity.this, "牛逼啊大爷!猜对了。。。", Toast.LENGTH_LONG).show(); } else if (inputnum < rand) {//猜小 Toast.makeText(Main2Activity.this, "猜小了。。。还有" + num+"次机会", Toast.LENGTH_LONG).show(); } else {//猜大 Toast.makeText(Main2Activity.this, "猜大了。。。还有" + num+"次机会", Toast.LENGTH_LONG).show(); } } }else{//机会用完提示 Toast.makeText(Main2Activity.this, "大爷你玩完了", Toast.LENGTH_LONG).show(); } } }); reset.setOnClickListener(new View.OnClickListener() {//监听重置按钮 @Override public void onClick(View v) { rand = random.nextInt(10);//重新产生随机数 num=5;//机会重置 Toast.makeText(Main2Activity.this, "随机数重置", Toast.LENGTH_LONG).show(); } }); } }
标签:trim 游戏 long tool cal 影响 creat int next
原文地址:https://www.cnblogs.com/easyidea/p/10498688.html