java学习之猜数字小游戏

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

java学习之猜数字小游戏

  2021-04-03 我要评论

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

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

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 + "次!");
 }
 
}
您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们