android猜数字游戏

android猜数字游戏

android猜数字游戏

android猜数字游戏

android猜数字游戏
猜数字游戏大家都懂的,直接上代码
package com.guessnum;

import java.util.Random;

public class Guess {
 private Random random;
 
 public int  GetRandomNum() {
return random.nextInt(100);
}
 
 public int  JugeNum(int n,int num) {
if(n>num){
return 1;}
else if (n
return 2;
}
else if (n==num) {
return 0;
}
else {
return -1;
}
}
 public Guess() {
super();
random=new Random();
}

 public String  play(int num,int n) {
if(JugeNum(num ,n)==0){
return "猜对了";}
else if(JugeNum(num,n)==2){
return "大了";}
else if(JugeNum(num,n)==1){
return "小了";}
else if(JugeNum(num,n)==-1){
return "数据有误";}
return "数据有误";
 }


}

package com.guessnum;

import junit.framework.Test;
import android.os.Bundle;
import android.R.integer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

MainActivity
public class MainActivity extends Activity {
private Button guess;
private Button playAgain;
private EditText numEditText;
private TextView showTextView;
private Guess g; 
private int num;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
guess=(Button)findViewById(R.id.button1);
playAgain=(Button)findViewById(R.id.button2);
numEditText=(EditText)findViewById(R.id.editText1);
showTextView=(TextView)findViewById(R.id.textView1);
g=new Guess();
num=g.GetRandomNum();
guess.setOnClickListener(new MyListener());
playAgain.setOnClickListener(new MyListener());
}
//button监听
class MyListener implements android.view.View.OnClickListener{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.equals(guess)){
showTextView.setText(g.play(num,Integer.parseInt(numEditText.getText().toString())));
}
if (v.equals(playAgain)) {
showTextView.setText("欢迎猜数字");
num=g.GetRandomNum();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}


你可能感兴趣的:(android)