猜数字游戏Java代码

合集下载

实验三Java猜数字游戏开发

实验三Java猜数字游戏开发

实验三Java猜数字游戏开发课程:Java实验班级:201352 姓名:程涵学号:20135210成绩:指导教师:娄佳鹏实验⽇期:15.06.03实验密级:预习程度:实验时间:仪器组次:必修/选修:选修实验序号:3实验名称: Java猜数字游戏开发(姬梦馨、程涵⼩组)⼀、实验⽬的与要求:通过编写Java的应⽤系统综合实例——猜数字游戏,总结、回顾和实践⾯向对象的编程思想以及编程⽅法,并通过编写程序来掌握Java语⾔编程技巧,将学习到的知识融会贯通,同时提⾼调试程序的能⼒,养成良好的编程习惯,并增强对程序设计整体思路的把握。

⼆、设备与环境硬件:MacBookAir软件:JDK 1.8.0; eclipse三、实验内容(1)实验需求分析:1.玩家输⼊⼀个数字,数字的范围在1-100之间,系统获取随机数。

2.对玩家输⼊的数字进⾏判断⼤⼩,如果不是系统要求的数字,系统将提⽰您,您输⼊的不是数字请重新输⼊,给出提醒以便玩家进⼀步选择。

3. 玩家猜中时系统给出所⽤时间和游戏⽔平的判断,系统给出是否继续的提⽰及判断。

4.系统根据您猜数字的次数,⾃动计数.5. 直到⽤户猜到数字为⽌,提⽰信息是否继续猜数字,如果继续将进⼊下⼀次游戏,如果退出将退出游戏系统.(2)功能模块详细设计1.随机数的获取功能描述:玩家输⼊⼀个数字,数字的范围在1-100之间,系统获取随机数。

2 输⼊输出模块功能描述:对玩家输⼊的数字进⾏判断和提⽰。

如果玩家输⼊的不是系统要求的数字,系统将提⽰您,您输⼊的不是数字请重新输⼊.。

如果玩家输⼊的数字与随机⽣成数相⽐较,⽐随机⽣成数⼩.系统提⽰您,数字太⼩请您重新输⼊。

如果玩家输⼊的数字与随机⽣成数相⽐较,⽐随机⽣成数⼤.系统提⽰您,数字太⼤请您重新输⼊。

3 判断模块功能描述:系统给出对其⽔平的判断和是否继续的提⽰;对玩家要求判断执⾏。

4 ⾃动计数模块功能描述:系统根据您猜数字的次数,⾃动计数.5 结果输出模块功能描述:直到⽤户猜到数字为⽌,提⽰信息是否继续猜数字,如果继续将进⼊下⼀次游戏,如果退出将退出游戏系统.(3)代码如下图所⽰:代码:import java.util.InputMismatchException;import java.util.Scanner;public class Main {public static void main(String[] args) {// 产⽣⼀个随机数int number = (int) (Math.random() * 100) + 1;// 加⼊countint count = 0;// 在这⾥加⼊最⼤值,和最⼩值int max = 100;int min = 1;while (true) {// 键盘录⼊数据Scanner sc = new Scanner(System.in);System.out.println("欢迎进⼊“猜数字游戏”");System.out.println("请输⼊你猜得数字:(" + min + "~" + max + ")"); try {count++;int guessNumber = sc.nextInt();// 判断if (guessNumber > number) {max = guessNumber;System.out.println("猜⼤了");}else if (guessNumber < number) {min = guessNumber;System.out.println("猜⼩了");}else {System.out.println("恭喜你,只⽤了" + count + "次就猜中了!"); // 问是否继续System.out.println("请问还要继续吗?(yes)");sc = new Scanner(System.in);String str = sc.nextLine();if ("yes".equals(str)) {// 重写赋值随机数number = (int) (Math.random() * 100) + 1;count = 0;max = 100;min = 1;}else {break;}}}catch (InputMismatchException e) {System.out.println("你输⼊的数据有误");}}}}(3).游戏运⾏结果截图四、实验结果及分析通过此次Java综合性实验,我对Java有了系统的了解。

java猜数字游戏源代码

java猜数字游戏源代码

import WindowButton extends JFrame implements ActionListener{ /****/private static final long serialVersionUID = 1L;int number;JTextField inputNumber;JLabel feedBack;JButton buttonGetNumber,buttonEnter;WindowButton(String s){super("猜数字小游戏");buttonGetNumber=new JButton("得到一个随机数");feedBack=new JLabel("无反馈信息",;;inputNumber=new JTextField("0",5);buttonEnter=new JButton("确定");(this);(this);(this);Box boxH1=();(new JLabel("获取1-100之间的随机数:"));(buttonGetNumber);Box boxH2=();(new JLabel("输入您的猜测: "));(inputNumber);Box boxH3=();(new JLabel("单击确定按钮: "));(buttonEnter);Box boxH4=();(new JLabel("反馈信息: "));(feedBack);Box baseBox=();(boxH1);(boxH2);(boxH3);(boxH4);Container con=getContentPane();(new FlowLayout());(baseBox);();setBounds(120,125,279,200);setVisible(true);setDefaultCloseOperation;setBounds(100,100,150,150);setVisible(true);validate();}public void actionPerformed(ActionEvent e){ if()==buttonGetNumber){number=(int)()*100)+1;}else if()==buttonEnter){int guess=0;try{guess=());if(guess==number){(this,"猜对了");}else if(guess>number){(this,"猜大了");(null);}else if(guess<number){(this,"猜小了");(null);}}catch(NumberFormatException event){(this,"请输入数字字符");}}}}public class猜数字游戏 {public static void main(String args[]){ new WindowButton("猜数字小游戏");}}。

java实验报告猜数字

java实验报告猜数字
《Java程序设计》实验报告
实验一:猜数字
专业班级:通信工程2008级1班
姓名:
学号:
பைடு நூலகம்时间:
实验一:猜数字
1、实验目的:
让学生使用if-else分支和while循环语句解决问题。
2、实验要求:
编写一个java应用程序,实现如下功能:
※随机分配给客户一个1~100之间的整数。
※用户从键盘输入自己的猜测。
{
System.out.println("猜大了,请再猜:");
yourGuess=reader.nextInt();
}
else if(yourGuess<realNumber)
{
System.out.println("猜小了,请再猜:");
yourGuess=reader.nextInt();
}
}
System.out.println("猜对了!");
}
}
int yourGuess=0;
Scanner reader=new Scanner(System.in);
System.out.println("输入您的猜测:");
yourGuess=reader.nextInt();
while(yourGuess!=realNumber)
{
if(yourGuess>realNumber)
※程序返回提示信息,提示信息分别是“猜大了”、“猜小了”和“猜对了”。
※用户可根据提示信息再次输入猜测,直到提示信息是“猜对了”。
3、程序效果图(各位同学的效果图应该各不相同!)
4、程序代码(主要语句有注释!)

猜数字游戏源代码

猜数字游戏源代码

#include <stdio.h>#include <stdlib.h>#include <process.h>#include <time.h>int main(){printf("\t\t * *\n");printf("\t\t * *\n");printf("\t\t * *\n");printf("\t\t *\n");printf("\t\t *\n");printf("\t\t *\n");printf("\t\t *\n");printf("\n");printf("\t\t *\n");printf("This is a number guessing game.\nJust guess and enjoy it!\nYou should input a number like 1234\n");system("pause");//游戏提示intanswer[4],a=0,b=0,i=0,j=0,guess,g[4],times=0,times_limit=12,win=0,lose=0,best_grade=13,round =0,alter1=1,alter2=1,rank=0,score=0;char face;//变量声明do{round++;times=0;system("cls");printf("Round:%d\tRank:%d\tScore:%d\tBestgrade:%d\n",round,rank,score,best_grade);printf("You will have %d chances to give your answer in this round\n",times_limit);//round初始化for(i=0;i<4;i++){srand((unsigned)time(NULL));answer[i]=rand()%10;for(j=0;j<i;j++){if(answer[j]==answer[i]){answer[i]=rand()%10;j=-1;}}}//随机生成4位answer//测试行printf("The answer is %d%d%d%d\n",answer[0],answer[1],answer[2],answer[3]);do{times++;printf("%2d\t",times);a=0;b=0;//计次,a,b单次初始化scanf("%d",&guess);g[0]=guess/1000;g[1]=(guess-g[0]*1000)/100;g[2]=(guess-g[0]*1000-g[1]*100)/10;g[3]=guess-g[0]*1000-g[1]*100-g[2]*10;//输入求guess各位数字for(i=0;i<4;i++){for(j=0;j<4;j++){b=b+(answer[i]==g[j]&&i!=j);a=a+(answer[i]==g[j]&&i==j);}}if(a!=4) face=1;else face=2;printf("\t%dA%dB\t%c\n",a,b,face);//比较求a,b并输出比较结果if(a<4&&times==times_limit&&score>0){printf("Do you want to get an extra chance with one score?\ny(1)/n(0)\n");scanf("%d",&alter1);if(alter1==1){times--;score--;}}//用分数换次数}while(a!=4&&times<times_limit);//处理给出答案直至答案正确或机会用完if(a==4){printf("Congratulations!\nYou are right!\n");win++;if(times<best_grade) best_grade=times;rank++;times_limit--;score++;}else{printf("Sorry.\nYou are wrong!\nThe answer is %d%d%d%d\n",answer[0],answer[1],answer[2],answer[3]);lose++;}printf("Round:%d\tWin:%d\tLose:%d\tScore:%d\tRank:%d\tBestgrade:%d\n",round,win,lose,score,rank,best_grade);//结果处理if(rank<10){printf("Continue?\ny(1)/n(0)\n");scanf("%d",&alter2);}}while(alter2==1&&rank<10);//等级至顶前选择是否继续system("cls");printf("Game over!\n");printf("Win:%d\tLose:%d\tRank:%d\tBest grade:%d\n",win,lose,rank,best_grade);system("pause");return 0;//结束处理}。

猜数字小游戏JAVA程序报告

猜数字小游戏JAVA程序报告

JAVA程序设计报告——猜数字小游戏目录一、猜数字小游戏简介 (4)二、用户需求分析 (4)三、问题描述 (4)1.课程设计的任务2.课程设计的要求四、模块设计 (5)1.课程设计的要求2.功能模块设计3.流程图五、功能设计 (7)1 . 随机数的产生模块2 . 输入判断模块3 . 记录猜测次数模块4.计时模块5.输入输出模块6.成绩判断模块六、异常处理 (9)七、调试分析 (10)八、不足之处 (11)九、总结 (12)十、程序附页 (13)摘要猜数字是一款非常经典的脑力游戏,游戏规则简单,是消磨时间、锻炼脑力的好选择。

通过选择猜数字游戏这个题目,可以让我掌握Java中的包和类,并且可以灵活的使用my eclipse软件。

同时更加深入的了解字符界面的编程过程。

使我更熟练的掌握Java程序框架的搭建和类的创建格式。

在分析阶段,要进行面向对象的需求分析、系统设计、画出相应的需求分析图、系统设计模型图,这些工作更能锻炼我的逻辑思维,更能培养我思考的全面性。

让我学会了多角度思考问题,对我以后的编程奠定了更好的基础。

一、猜数字小游戏简介系统随机产生任意一个1—100的自然数,玩家输入数字,若输入的数字比随机生成数小,系统将提示,数字太小请您重新输入;如果输入的数字比随机生成数大,系统将提示,数字太大请您重新输入;若输入的字符不是合法字符,系统将提示,您输入的数字不合法,请从新输入,游戏开始时,系统自动记录您猜数字的时间和次数,结束后显示游戏共花费的次数和时间及对游戏结果的评价。

二、用户需求分析设计一个猜数字游戏程序,要求具体如下特性:a.输入任意一个数字。

数字的要求是1—100的自然数即可。

b.系统对您输入的数字进行判断。

如果玩家输入的数字与计算机随机生成数相比较,输入的数字比随机生成数小.系统将提示您,数字太小请您重新输入。

如果玩家输入的数字与计算机随机生成数相比较,如果输入的数字比随机生成数大。

系统将提示您,数字太大请您重新输入。

android猜数字游戏程序代码以及效果图

android猜数字游戏程序代码以及效果图

android真机测试运行效果图如下:以下是MainActivity.java文件//*************MainActivity.java************************* package com.example.guessinggame;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {private Button easyBtn; //响应“简单”按钮private Button normalBtn;//响应“标准”按钮private Button hardBtn; //响应“困难”按钮@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);initControl(); //初始化控件}//初始化控件public void initControl(){easyBtn = (Button)findViewById(R.id.easy);normalBtn = (Button)findViewById(R.id.normal);hardBtn = (Button)findViewById(R.id.hard);}//响应button点击事件public void clickButton(View v){Intent intent = new Intent(MainActivity.this , GuessingGame.class);switch (v.getId()) {case R.id.easy:intent.putExtra("numOfData", 3);intent.putExtra("guessNums", 8);startActivity(intent);break;case R.id.normal:intent.putExtra("numOfData", 4);intent.putExtra("guessNums", 10);startActivity(intent);break;case R.id.hard:intent.putExtra("numOfData", 5);intent.putExtra("guessNums", 15);startActivity(intent);break;default:break;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}以下是GuessingGame.java文件//***************GuessingGame.java****************package com.example.guessinggame;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.DialogInterface.OnClickListener;import android.graphics.Paint;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.view.KeyEvent;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnKeyListener;import android.widget.Button;import android.widget.EditText;import android.widget.ImageButton;import android.widget.TextView;import android.widget.Toast;public class GuessingGame extends Activity{private int guessNums; //猜测总次数private int guessCounts;//猜测次数统计private int numOfData; //给定猜测的位数private int[] randomNum; //生成随机数// private int countNums; //用户输入数字的位数统计private int[] userInputNum; //用户输入数字private StringBuffer ARight; //已经猜对的数字private int ARightLength; //ARight的长度private List<Integer> list; //用于记录用户按下的数字private ToolMethods toolMth; //获取随机数方法类private EditText editAnswer; //显示输入的答案private TextView guessingInfo;//显示猜测结果private ImageButton imageBtn; //提示按钮private Button createNum; //生成随机数按钮private Button answerBtn; //查看答案private Button guessBtn; //“开始猜”按钮private Button[] numButtons; //拥有0~9数字的button按钮//拥有0~9数字的ID号private int[] numButtonsID = {R.id.zero , R.id.one , R.id.two ,R.id.three , R.id.four , R.id.five ,R.id.six ,R.id.seven , R.id.eight , R.id.nine};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.guessing);init(); //初始化}private void init() {// 数据初始化int temp = 0;temp = getIntent().getIntExtra("guessNums", 0);guessNums = temp;temp = getIntent().getIntExtra("numOfData", 0);numOfData = temp;guessCounts = 0;randomNum = new int[numOfData];// countNums = 0;userInputNum = new int[numOfData];//方法类初始化toolMth = new ToolMethods();//控件初始化editAnswer = (EditText)findViewById(R.id.editAnswer);guessingInfo = (TextView)findViewById(R.id.guessingInfo);imageBtn = (ImageButton)findViewById(R.id.imageBtn);createNum = (Button)findViewById(R.id.randomNum);answerBtn = (Button)findViewById(R.id.answer);guessBtn = (Button)findViewById(R.id.guess);numButtons = new Button[10];for(int i = 0; i < 10; i++){numButtons[i]=(Button)findViewById(numButtonsID[i]);}createNum.setText("随机生成" + numOfData + "位数");editAnswer.setOnKeyListener(new onKeyListener());//输入框响应事件editAnswer.addTextChangedListener(new textWatcher());//输入字符串超过长度响应事件//getApplicationContext()对于整个应用处于运行期间有效toolMth.showDialog(GuessingGame.this , "吴康大侠,您好!", 3000, false, true);}//输入字符串超过长度响应事件public class textWatcher implements TextWatcher{private int selectionStart = 0;private int selectionEnd = 0;private CharSequence temp = null;@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {temp = s;}@Overridepublic void afterTextChanged(Editable s) {selectionStart = editAnswer.getSelectionStart();selectionEnd = editAnswer.getSelectionEnd();if(temp.length() > numOfData){Toast.makeText(GuessingGame.this, "请不要超过" + numOfData + "位数", Toast.LENGTH_SHORT).show();s.delete(selectionStart-1, selectionEnd);int tempSelection = selectionStart;editAnswer.setText(s);editAnswer.setSelection(tempSelection);}}}//输入框响应事件public class onKeyListener implements OnKeyListener{@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_DEL){if(editAnswer.getText().toString().length() < numOfData){for(Button tempBtn : numButtons){tempBtn.setEnabled(true);}}editAnswer.requestFocus();}if(keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1 || keyCode == KeyEvent.KEYCODE_2 ||keyCode == KeyEvent.KEYCODE_3 || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5 ||keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7 || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9){judgeNumsCount();}return false;}}//响应产生随机数的函数public void createNum(View v){randomNum = toolMth.createNum(numOfData);editAnswer.setVisibility(View.VISIBLE);createNum.setText("不重复的" + numOfData + "位数");createNum.setEnabled(false);answerBtn.setEnabled(true);guessBtn.setEnabled(true);for(int i = 0; i < 10; i++){numButtons[i].setEnabled(true);}}//响应0~9数字按钮的函数public void numButton(View v){for(int i = 0; i < 10; i++){if(v == numButtons[i]){//获取光标的位置int index = editAnswer.getSelectionStart();Editable editable = editAnswer.getText();editable.insert(index, numButtons[i].getText().toString());judgeNumsCount();break;}}}public void judgeNumsCount(){list = new ArrayList<Integer>();//当“输入位数”==“给定猜测的位数”时,数字按钮将失效if(editAnswer.getText().toString().length() == numOfData){for(Button tempBtn : numButtons){tempBtn.setEnabled(false);}int temp = Integer.parseInt(editAnswer.getText().toString());int[] tempNum = new int[numOfData];for(int j = 0; j < numOfData; j++){tempNum[j] = temp % 10;temp = temp/10;}for(int j = numOfData - 1; j >= 0 ; j--){list.add(tempNum[j]);}}else{for(Button tempBtn : numButtons){tempBtn.setEnabled(true);}}}public void guessButton(View v){int Acounts = 0; //统计A的次数int Bcounts = 0; //统计B的次数ARight = new StringBuffer("你已经猜对了:");ARightLength = ARight.length();if(v == guessBtn){if(editAnswer.getText().toString().length() !=numOfData){Toast.makeText(this, "请输入" + numOfData + "位数,不然不能猜的(⊙o⊙)哦~~", Toast.LENGTH_LONG).show();}else if(!toolMth.isRepeated(list)){Toast.makeText(this, "请不要输入重复数字", Toast.LENGTH_LONG).show();}else{judgeNumsCount();for(int i = 0; i < list.size(); i++){userInputNum[i] = list.get(i).intValue();}guessCounts++; //统计已经猜的次数for(int i = 0; i < numOfData; i++)for(int j = 0; j < numOfData; j++){if(userInputNum[i] == randomNum[j]){if(i == j){Acounts++; //统计A的次数ARight.append(userInputNum[i] + " 、");}else Bcounts++; //统计B的次数}}if(guessCounts == guessNums){if(Acounts == numOfData){toolMth.showDialog(GuessingGame.this, "您在最后一次机会中猜对了答案,恭喜您!", 3000, true, false);StringBuffer showStr = new StringBuffer(guessingInfo.getText().toString());showStr.append("\n" + editAnswer.getText().toString() + "---->" + Acounts + "A" + Bcounts + "B");guessingInfo.setText(showStr);}else{AlertDialog.Builder builder = new AlertDialog.Builder(GuessingGame.this).setTitle("可惜...").setMessage("已经超过" + guessNums + "次").setIcon(R.drawable.sad).setPositiveButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create().show();}editAnswer.setVisibility(View.INVISIBLE);createNum.setText("随机生成" + numOfData + "位数");createNum.setEnabled(true);guessBtn.setEnabled(false);answerBtn.setEnabled(false);guessingInfo.setText("");guessCounts = 0;ARight.delete(0, ARight.length());}else if(Acounts == numOfData){if(guessCounts == 1){toolMth.showDialog(GuessingGame.this, "您在第一次就猜对了答案,太厉害了!", 3000, true, false);}else{toolMth.showDialog(GuessingGame.this, "恭喜您猜对了!", 3000, true, false);}StringBuffer showStr = new StringBuffer(guessingInfo.getText().toString());showStr.append("\n" + editAnswer.getText().toString() + "---->" + Acounts + "A" + Bcounts + "B");editAnswer.setVisibility(View.INVISIBLE);guessingInfo.setText(showStr);createNum.setText("随机生成" + numOfData + "位数");createNum.setEnabled(true);guessBtn.setEnabled(false);answerBtn.setEnabled(false);guessingInfo.setText("");guessCounts = 0;ARight.delete(0, ARight.length());}else{toolMth.showDialog(GuessingGame.this, "您没有猜对!", 3000, false, false);StringBuffer showStr = new StringBuffer(guessingInfo.getText().toString());showStr.append("\n" + editAnswer.getText().toString() + "---->" + Acounts + "A" + Bcounts + "B");guessingInfo.getPaint().setFakeBoldText(true);guessingInfo.getPaint().setAntiAlias(true);guessingInfo.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);guessingInfo.setText(showStr);}// countNums = 0;for(Button tempBtn : numButtons){tempBtn.setEnabled(true);}if(editAnswer.getText().toString().length() == numOfData){editAnswer.setText("");}}}}public void imageButton(View v){if(v == imageBtn){String tempTitle,tempMessage;if(ARight == null || ARight.length() <= 0){tempTitle = "提示:";tempMessage = "请开始吧!";}else if(ARight.length() == ARightLength){tempTitle = "可惜…";tempMessage = "抱歉,你没有答对";}else{tempTitle = "提示:";tempMessage = ARight.substring(0, ARight.length()-1);}AlertDialog.Builder builder = new AlertDialog.Builder(GuessingGame.this);builder.setTitle(tempTitle).setMessage(tempMessage).setPositiveButton("确定", new OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});builder.create().show();}}public void answerButton(View v){StringBuffer answerStr = new StringBuffer();for(int temp : randomNum){answerStr.append(temp);}AlertDialog.Builder builder = new AlertDialog.Builder(GuessingGame.this);builder.setTitle("答案如下:").setMessage(answerStr).setPositiveButton("确定", new OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});builder.create().show();}public boolean onCreateOptionsMenu(Menu menu) {super.onCreateOptionsMenu(menu);/** add()方法的四个参数,依次是:1、组别,如果不分组的话就写Menu.NONE,* 2、Id,这个很重要,Android根据这个Id来确定不同的菜单3、顺序,那个菜单现在在前面由这个参数的大小决定* 4、文本,菜单的显示文本*/menu.add(1, 1, 1, "帮助");menu.add(1, 2, 2, "关于");return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {AlertDialog.Builder builder = new AlertDialog.Builder(this);switch (item.getItemId()) {case 1:builder.setTitle("帮助").setMessage(R.string.guessingGame).setPositiveButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create().show();break;case 2:builder.setTitle("关于").setMessage("玉树临风,嘿嘿~~").setPositiveButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create().show();break;default:break;}return super.onOptionsItemSelected(item);}}以下是ToolMethods.java文件//****************** ToolMethods.java**************** package com.example.guessinggame;import java.util.HashSet;import java.util.List;import java.util.Set;import android.content.Context;import android.view.Gravity;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.Toast;public class ToolMethods {//public int[] createNum(int numOfData) {int[] randomNum = new int[numOfData];int i = 0;String[] tempArray;do{tempArray = getNumber(numOfData);}while(!isRepeated(tempArray));for(String tempNum : tempArray){randomNum[i++] = Integer.parseInt(tempNum);}return randomNum;}//生成随机数(字符串类型)private String[] getNumber(int numOfData) {String[] tempArray = new String[numOfData];for(int i = 0; i < numOfData; i++){int tempNum = (int)(Math.random()*10);tempArray[i] = String.valueOf(tempNum);}return tempArray;}//验证随机数是否重复private boolean isRepeated(String[] tempArray) {Set<String> set = new HashSet<String>();for(String tempStr : tempArray){set.add(tempStr);}if(set.size() != tempArray.length){return false;}return true;}//验证随机数是否重复public boolean isRepeated(List<Integer> list) {Set<Integer> set = new HashSet<Integer>();for(int i = 0; i < list.size(); i++){set.add(list.get(i));}if(set.size() != list.size()){return false;}return true;}public void showDialog(Context context, String message, int milliseconds, boolean useSmileImage, boolean useCoolImage){Toast dialog = Toast.makeText(context, message, Toast.LENGTH_LONG);dialog.setGravity(Gravity.CENTER, 0, 0);LinearLayout dialogView = (LinearLayout)dialog.getView();ImageView useImage = new ImageView(context);if(useSmileImage){useImage.setImageResource(R.drawable.smile);}else if(useCoolImage){useImage.setImageResource(R.drawable.cool);}else{useImage.setImageResource(R.drawable.sad);}dialogView.addView(useImage, 0);dialog.setDuration(milliseconds);dialog.show();}}。

猜数游戏完整代码

猜数游戏完整代码

/**猜数游戏的完整代码*/import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Scanner;public class GuessNumber_all{public static void compareNum(){ //使用BufferedReader读入数据流try{//获取随机产生的数字int random=(int)(Math.random()*100+1);for( int i=1;;i++){BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("请猜数:");int keyBoardNum=Integer.parseInt(br.readLine()); //获取键盘输入的数字//比较两数的大小if(keyBoardNum!=random){if(keyBoardNum>random){System.out.println("大了");}else{System.out.println("小了");}}else{System.out.println("随机数是"+random);System.out.println("恭喜你猜对了,你的战斗力是:"+(int)((1-i/8.0f)*100));break;}if(i>=8){System.out.println("超过次数,尚需努力");System.out.println("正确答案是:"+random);break;}}}catch (Exception e){System.out.println("输入错误,请重新输入");}}public static void GameSet(){System.out.println(" 游戏难度设置:1 :容易 2 :一般3:难");int select=getInput();switch(select){case 1:Easy();break;//处理1:容易case 2:Middle();break;//处理2:一般case 3:Difficult();break;//处理3:难default:System.out.println("程序结束");return;}}public static int getInput(){//从键盘获取数字输入,若输入非数字字符,返回-1int res=-1;try{Scanner x=new Scanner(System.in);//构造一个Scanner对象,其传入参数为System.inres=x.nextInt();}catch(Exception e){//通过异常处理来捕获输入的字符/**System.out.println("非法输入,请重新选择:");rentInVechile(); */}return res;}public static void Easy(){try{//获取随机产生的数字int random=(int)(Math.random()*100+1);for( int i=1;;i++){BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("请猜数:");intkeyBoardNum=Integer.parseInt(br.readLine()); //获取键盘输入的数字//比较两数的大小if(keyBoardNum!=random){if(keyBoardNum>random){System.out.println("大了");}else{System.out.println("小了");}}else{System.out.println("随机数是"+random);System.out.println("恭喜你猜对了,你的战斗力是:"+(int)((1-i/8.0f)*100));break;}if(i>=8){System.out.println("超过次数,尚需努力");System.out.println("正确答案是:"+random);break;}}}catch (Exception e){System.out.println("输入错误,请重新输入");}}public static void Middle(){{//获取随机产生的数字int random=(int)(Math.random()*100+1);for( int i=1;;i++){BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("请猜数:");intkeyBoardNum=Integer.parseInt(br.readLine()); //获取键盘输入的数字//比较两数的大小if(keyBoardNum!=random){if(keyBoardNum>random){System.out.println("大了");}else{System.out.println("小了");}else{System.out.println("随机数是"+random);System.out.println("恭喜你猜对了,你的战斗力是:"+(int)((1-i/6.0f)*100));break;}if(i>=6){System.out.println("超过次数,尚需努力");System.out.println("正确答案是:"+random);break;}}}catch (Exception e){System.out.println("输入错误,请重新输入");}}public static void Difficult(){try{//获取随机产生的数字int random=(int)(Math.random()*100+1);for( int i=1;;i++){BufferedReader br=new BufferedReader(new InputStreamReader(System.in));System.out.println("请猜数:");intkeyBoardNum=Integer.parseInt(br.readLine()); //获取键盘输入的数字//比较两数的大小if(keyBoardNum!=random){if(keyBoardNum>random){System.out.println("大了");}else{System.out.println("小了");}}else{System.out.println("随机数是"+random);System.out.println("恭喜你猜对了,你的战斗力是:"+(int)((1-i/4.0f)*100));break;}if(i>=4){System.out.println("超过次数,尚需努力");System.out.println("正确答案是:"+random);break;}}}catch (Exception e){System.out.println("输入错误,请重新输入");}}//处理主窗体public static int readSelect(BufferedReader br) {int select=0;while(true){try{System.out.println("请输入您的选择");String s=br.readLine();select=Integer.parseInt(s);if(select>=1 && select<=3)break;System.out.println("无效选择");}catch(Exception ex){System.out.println("请输入数字!");}}return select;}public static void main(String[] args) {System.out.println("请输入一个(0-100)之间的一个数");BufferedReader br=new BufferedReader(new InputStreamReader(System.in));while(true){System.out.println("1.开始猜数");System.out.println("2.游戏参数设置");System.out.println("3.退出");int select=readSelect(br);switch(select){case 1:compareNum();break;case 2:GameSet();break;case 3:System.out.println("程序结束");return;}}}}。

使用JavaBean实现猜数字小游戏(Web实验)

使用JavaBean实现猜数字小游戏(Web实验)

使⽤JavaBean实现猜数字⼩游戏(Web实验)要求:游戏随机给出⼀个1—100(包括1和100)的数字,然后让你猜是什么数字。

游戏会提⽰太⼤或太⼩,从⽽缩⼩结果范围。

实例包含⼀个JavaBean(GessNumber.java)和两个JSP页⾯:guess.jsp,getNumber.jsp。

思路:使⽤ecplise,要通过javaBean实现,那么⾸先创建javaBean,然后再创建产⽣随机数的getNumber.jsp页⾯和可以交互对错的guess.jsp页⾯。

JavaBean:简单的说,JavaBean是遵循特殊规范的Java类。

按功能分,可以分为可视Bean和不可视两类。

可视Bean是在画⾯上可以显⽰的Bean,通过属性接⼝接收数据并显⽰在画⾯。

不可视Bean即JSP中时常使⽤的Bean,在程序的内部起作⽤,如⽤于求值、存储⽤户数据等。

1package chapter;//GuessNumber.java23public class GuessNumber {4private int answer=0;//⽣成的随机数5private int guessNumber=0;//⽤户猜的数6private int guessCount=0;//猜的次数7private String result=null;//返回的结果8private boolean right=false;//判断标志9public void setAnswer(int answer) {10this.answer=answer;11 guessCount=0;12 }13public int getAnswer()//这⾥写错了,写成了getAnser,导致报错Cannot find a method to read property [answer] in a bean of type [chapter.GuessNumber]14 {15return answer;16 }17public void setGuessNumber(int guessNumber) {//javabean必要的每个封装的属性都有set和get⽅法18this.guessNumber=guessNumber;19 guessCount++;20if(guessNumber==answer)21 {22 result="恭喜你,猜对了!";23 right=true;24 }25else if(guessNumber>answer)26 {27 result="对不起,你猜⼤了!";28 right=false;2930 }31else32 {33 result="对不起,你猜⼩了!";34 right=false;35 }36 }37public int getGuessNumber() {38return guessNumber;39 }40public int getGuessCount()41 {42return guessCount;43 }44public String getResult() {45return result;46 }47public boolean isRight() {//boolean型需要isxxx()⽅法48return right;49 }50public void setRight(boolean right)51 {52this.right=right;53 }5455 }需要注意的是ecplise中的javabean需要创建在当前项⽬的src中,先新建packge,再新建class。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

import java.util.Random;
import javax.swing.JOptionPane;
public class GuessNumber{
public static void main(String[]args){
//TODO Auto-generated method stub
int start=JOptionPane.showConfirmDialog(null,"猜数字,游戏开始?","游戏开始",JOptionPane.YES_NO_CANCEL_OPTION);
if(start==JOptionPane.YES_NO_OPTION){
int num=(new Random().nextInt(100));
String inputValue;//保存用户输入字符串
int inputuNum;//保存字符串转换的整数
int i=1;//记录猜数的次数
while(i<=8){
inputValue=JOptionPane.showInputDialog("请输入一个0^100的整数\n,共8次机会,这是第"+i+"次");
int inputNum=Integer.parseInt(inputValue);
if(inputNum==num){
JOptionPane.showMessageDialog(null,"恭喜您,猜对啦!","猜数字游戏",RMATION_MESSAGE);
break;
}
else if(inputNum>num)
JOptionPane.showMessageDialog(null,"您猜的数字偏大!","猜数字游戏",JOptionPane.WARNING_MESSAGE);
else
JOptionPane.showMessageDialog(null,"您猜的数字偏小!","猜数字游戏",JOptionPane.WARNING_MESSAGE);
i++;
}
if(i>8)
JOptionPane.showMessageDialog(null,"8次机会用尽,游戏结束!","游戏结束",JOptionPane.ERROR_MESSAGE);
}
else
JOptionPane.showMessageDialog(null,"退出游戏","猜数字游戏",RMATION_MESSAGE);
} }。

相关文档
最新文档