java中怎么实现一个猜数字小游戏

发布时间:2021-06-14 12:19:32 作者:Leah
来源:亿速云 阅读:227

java中怎么实现一个猜数字小游戏,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

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中怎么实现一个猜数字小游戏问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. linux如何实现猜数字小游戏
  2. Java如何实现猜数字小游戏

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何在易语言中使用变量表

下一篇:Spring中如何进行日常Bug排查

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》