现在的位置: 首页 > 编程语言 > 正文

java学习之猜数字小游戏

2020年02月14日 编程语言 ⁄ 共 2190字 ⁄ 字号 评论关闭

今天主要学习了一些初级的设计,完成了这个猜数字的小游戏,其是也算不上是什么游戏,因为我答案都给出来了。当然也是想对代码更加熟练的操作,让自己能够得心应手。

这个小程序中让我花了点时间的主要是那个如何去重的问题,当时也是思考良久,后来才考虑到使用死循环让随机数产生直到不重复为止,其他感觉也还好。

import java.util.Scanner; public class GuessingGames { public static void main(String[] args) { Scanner in=new Scanner(System.in); char[] chs=generate(); System.out.println(chs); int score=500; while(true) { System.out.println("请猜猜看!"); String str=in.next(); char[] input=str.toCharArray(); //将用户输入的字符串转换为数组 int[] result=compare(chs, input); if (result[1]==chs.length) { System.out.println("恭喜你,猜对了!!!你获得的分数为"+score+"猜错次数为:"+(500-score)/10); break; }else { System.out.println("字符猜对个数为:"+result[0]+","+"位置猜对为:"+result[1]); score-=10; } } } // 随机生成字母 public static char[] generate() { char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; char[] chs = new char[5]; char copy; for (int i = 0; i < chs.length; i++) { chs[i] = letters[(int) (Math.random() * 26)]; copy=letters[(int) (Math.random()*26)]; for (int j = 0; j < i; j++) { if (chs[i]==chs[j]) { for(;;) { copy=letters[(int) (Math.random()*26)]; if (chs[i]!=copy) { chs[i]=copy; break; } } } } } return chs; } //完成两个数组的对比 public static int[] compare(char[] chs,char[] input) { int[] score=new int[2]; for (int i = 0; i < input.length; i++) { for (int j = 0; j < chs.length; j++) { if (input[i]==chs[j]) { score[0]++; if (i==j) { score[1]++; } break; } } } return score; }}

小编再为大家分享一段代码:Java控制台猜数字小游戏:

import java.util.*; /** *控制台猜数字小游戏,系统自动生成范围为1-100的数字 *@version 1.0 2018-01-04 *@author jie1024(wechat:wxxueba) */public class GuessX{ public static void main(String[] args){ Random random = new Random();//创建random int x = random.nextInt(100)+1;//生成一个1-100之间的随机数 random.nextInt(100)的范围为0-99,所以+1,范围为1-100 System.out.println("系统已自动为您生成了一个随机数(范围为1-100),游戏开始!"); System.out.print("猜猜这个数字是多少吧:"); Scanner in = new Scanner(System.in);//创建scanner int y = in.nextInt(); //输入数字 int count = 1; //次数 while(y != x){ count ++; if(y<1 || y>100){ System.out.print("Sorry,你猜的数字不在范围之内(范围为1-100),请再重新猜一次吧:"); y = in.nextInt(); } else if (y>x){ System.out.print("Sorry,你输入的数字太大了,请再重新猜一次吧:"); y = in.nextInt(); } else if (y<x){ System.out.print("Sorry,你输入的数字太小了,请再重新猜一次吧:"); y = in.nextInt(); } } System.out.println("恭喜你,猜对了!你猜的数字是" + y + "你总共猜了" + count + "次!"); } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

本文标题: java学习之猜数字小游戏

以上就上有关java学习之猜数字小游戏的全部内容,学步园全面介绍编程技术、操作系统、数据库、web前端技术等内容。

抱歉!评论已关闭.